I reviewed this question/answer here before writing this: Declare and Initialize String Array in VBA
I am trying to understand the proper way to declare and initialize an array WITHOUT resorting to data type VARIANT.
This is my code, and it does work as it is:
Function MakeLegalFilename(legalname As String) As String
Dim MyArray() As Variant
Dim x As Integer
MyArray = Array("<",">","?","@","%")
For x = LBound(MyArray) To UBound(MyArray)
legalname = Replace(legalname, MyArray(x), "", 1)
Next x
MakeLegalFilename = legalname
End Function
If I change "Variant" to "String," the code fails at MyArray = Array(...
with a runtime error 13 type mismatch.
If I define the array size to match the number of characters in the string (5 total, but array starts at 0):
Dim MyArray(4) As String
MyArray = Array("<",">","?","@","%")
Now I get a compile error at MyArray = Array(...
that says "Can't assign to array."
I know that I could declare the array this way and make it work (I tested it this way):
MyArray(0) = "<"
MyArray(1) = ">"
MyArray(2) = "?"
...
MyArray(4) = "%"
But if I am coding in a whole list of characters (say 20), then doing this is cumbersome, and plus, I would like to know why the other way doesn't work, since it suggests I have a fundamental misunderstanding. In it's most basic form, my question really is, why doesn't this:
Dim MyArray(4) As String
MyArray = Array("<",">","?","@","%")
work?
Thank you.