I am working on a script that inserts various types of data into a worksheet (ws).
Dim ws as Worksheet
Dim Index_Array(0 to 5) As Variant
Dim i as Integer
Set ws = ActiveSheet
Index_Array(0) = "This is some text."
Index_Array(1) = "This is also some text."
Index_Array(2) = "22004"
Index_Array(3) = 42
Index_Array(4) = 2.34657
Index_Array(5) = "=55" 'Yes, this should in fact be a string, not a formula or a number
For i = LBound(Index_Array) To UBound(Index_Array)
ws.Cells(1, i + 1).Value = Index_Array(i)
Next i
The problem is when I try to insert the string =55
into cell A5, it gives me
Run-time Error 1004: Application-defined or object-defined error.
The script is all working perfectly fine except in this case, and I believe it is because it is trying to make it a formula. I don't want to force everything to start with a '
character because not everything is a string. Is there an easy way to make Excel accept a string that starts with an equal sign as a cell value?
Adds a ' in front of each array item and makes it a text in the Excel UI.
so
Dim ws As Worksheet
Dim Index_Array(0 To 5) As Variant
Dim i As Integer
Set ws = ActiveSheet
Index_Array(0) = "This is some text."
Index_Array(1) = "This is also some text."
Index_Array(2) = "22004"
Index_Array(3) = 42
Index_Array(4) = 2.34657
Index_Array(5) = "=55"
For i = LBound(Index_Array) To UBound(Index_Array)
ws.Cells(1, i + 1).value = "'" & Index_Array(i) ' add a "'" to make it a text value in excel UI
Next
I think the correct way is to turn your value to string from first point.
first way:
Index_Array(5) = "'=55"
or
Index_Array(5) = cstr("'=55")
if you can't change the data when defining it, and only you want this happens to your data starting with =
, use an if with left(array(i),1) = "="
and add "'"
to first of that:
For i = LBound(Index_Array) To UBound(Index_Array)
if left(array(i),1) = "=" then
ws.Cells(1, i + 1).value= "'"& array(i)
else
ws.Cells(1, i + 1).value = array(i)
end if
next i
Regards,
M
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With