Line continuation not working in VBA for 2D Array construction

前端 未结 1 1029
隐瞒了意图╮
隐瞒了意图╮ 2021-01-24 07:55

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

相关标签:
1条回答
  • 2021-01-24 08:14

    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.

    0 讨论(0)
提交回复
热议问题