Line continuation not working in VBA for 2D Array construction

陌路散爱 提交于 2019-12-20 04:22:13

问题


In the following Subroutine, defining a two dimensional array doesn't seem to work with line continuation. TestArray1 initializes as expected, but when I add line continuation I get the message,

"Compile Error - Closing bracket missing".

(Actually I'm not sure of the exact wording in English, doing this in German. In German the error message is,

"Fehler beim Komilieren: Fehlende schliesende Klammer".

I'm sure the English is not far off.)
Why would this not work?

Sub TestArrays()


Dim TestArray1 As Variant, TestArray2 As Variant

TestArray1 = [{"1String1", "1String2", "1String3"; "2String1", "2String2", "2String3"; "3String1", "3String2", "3String3"}]

TestArray2 = [{"1String1", "1String2", "1String3"; _
"2String1", "2String2", "2String3"; _
"3String1", "3String2", "3String3"]}

End Sub

回答1:


Don't use square brackets.

Square brackets in VBA DO NOT stand for "this is an array", even though it looks like it (if you're any familiar with JSON anyway), and even though it might work.

Square brackets in VBA stand for "this is an expression that the host application will be evaluating at run-time".

In other words, it's giving work to Excel's expression evaluation engine: it's not VBA, it's Excel. The syntax of whatever is inside a square-bracketed expression must be legal in Excel's formula bar1.

Use the Array standard VBA function to create an array in VBA:

TestArray1 = Array("1String1", "1String2", "1String3", "2String1", "2String2", "2String3", "3String1", "3String2", "3String3")

Split it up with a line continuation at any point between two strings:

TestArray1 = Array( _
    "1String1", "1String2", _
    "1String3", "2String1", _
    "2String2", "2String3", _
    "3String1", "3String2", _
    "3String3")

Note that the inconsistent ; vs , separators are probably part of the problem: Excel formulas use your system's list separator character: that's the character you'll want to use in square-bracket expressions - but you don't need to do that, because you don't need any square-bracket expressions.

There is no syntax for inline-initializing a 2D array in VBA. Declare & size your array explicitly instead:

Dim my2D(1 To 10, 1 To 10)
my2D(1, 1) = "1string1"
'...

If you have that much hard-coded strings in your code, then you are coding data. Data belongs in storage, not in code. Read the data from a worksheet, you'll get a 2D variant array for free, with a one-liner, without abusing language syntax, and if the data needs to change, then the code doesn't:

Dim my2D As Variant
my2D = sourceRange.Value

1 unless it's a VBA foreign identifier, in which case Excel doesn't get to evaluate it. Just don't use square bracket expressions, they're confusing.



来源:https://stackoverflow.com/questions/59309658/line-continuation-not-working-in-vba-for-2d-array-construction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!