VBA - 错误“常量表达式需要”

时间:2021-06-20 04:26:18

标签: vba constants expression

我正在用 VBA 中的二维数组做实验,但在我附上照片时遇到了问题。如果有任何错误,你能帮忙吗?任何帮助将非常appriciated。 这是我的代码:

        Sub read_data()
     
        Dim rng As Range
        Set rng = Sheet1.Range("C8:G12")
       total_row = Sheet1.Range("C8:G12").Rows.Count
       total_col = Sheet1.Range("C8:G12").Columns.Count
        Dim arr2(total_row, total_col)
        
        arr2 = rng
        For i = 0 To total_row
            For j = 0 To total_col
                Debug.Print i, j, arr2(i, j)
            Next j
        Next i

End Sub

错误如下:

enter image description here

3 个答案:

答案 0 :(得分:0)

我认为系统要求您在需要确定数组大小时使用 constant variable,但是您不需要预先设置数组的大小,就像声明 {{1} } 作为数组,它会自动设置数组的大小。

此外,要找到数组的长度,最好使用数组的Range value,这里是有效且更短的代码:

Lbound & Ubound

引用(常量变量一旦被声明为开始,在执行过程中不能改变值):

https://docs.microsoft.com/en-us/office/vba/language/concepts/getting-started/declaring-constants

答案 1 :(得分:0)

您可以将范围内的值直接放入数组中,然后在循环中使用 contclass SubwayLine: def __init__(self, stations): self.stations = stations def __str__(self): return str(stations) keys = ['Line1', 'Line2', 'Line3', 'Line4'] values = subwayStation subwayStation = {} for line, stations in zip(keys, values): subwayStation[line] = SubwayLine(stations) print(subwayStation['Line1']) 来获取每个维度的下限/上限。

LBound

答案 2 :(得分:0)

' closest to the source code
Sub read_data()
     
    Dim rng As Range
    Set rng = Sheet1.Range("C8:G12")
    total_row = Sheet1.Range("C8:G12").Rows.Count
    total_col = Sheet1.Range("C8:G12").Columns.Count
    Dim arr2    ' remove (total_row, total_col)
    
    arr2 = rng
    For i = 1 To total_row      '1 instead 0
        For j = 1 To total_col  '1 instead 0
            Debug.Print i, j, arr2(i, j)
        Next j
    Next i

End Sub

'slightly improved

Sub read_data2()
    Dim arr2 As Variant, i As Long, j As Long
    
    With Sheet1.Range("C8:G12")
        arr2 = .Value
        For i = 1 To .Rows.Count
            For j = 1 To .Columns.Count
                Debug.Print i, j, arr2(i, j)
            Next j
        Next i
    End With
End Sub
相关问题