VBA - 错误 "Constant expression require "

VBA - error "Constant expression require "

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

        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

错误如下:

我认为系统要求你在确定数组大小时使用constant variable,但是你不需要预先设置数组的大小,因为当你声明一个Range value作为数组,它会自动设置数组的大小。

此外,要找到数组的长度,最好使用数组的Lbound & Ubound,这里是有效的代码,也更短:

Sub read_data()
Dim total_col As Long, i As Long, j As Long
Dim arr2

total_col = Sheet1.Range("C8:G12").Columns.Count
arr2 = Sheet1.Range("C8:G12")

For i = LBound(arr2) To UBound(arr2)
    For j = 1 To total_col
        Debug.Print arr2(i, j)
    Next j
Next i

End Sub

参考(常量变量一旦声明为开始就不能在执行过程中改变值):

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

您可以将范围内的值直接放入数组中,然后在循环中使用 LBoundUBound 以获得每个维度的 lower/upper 限制。

Sub read_data()
Dim rng As Range
Dim arr2 As Variant
Dim idxRow As Long  
Dim idxCol As Long

    Set rng = Sheet1.Range("C8:G12")
    arr2 = rng.Value
     
    For idxRow = LBound(arr2,1) To UBound(arr2,1)
        For idxCol = LBound(arr2,2) To UBound(arr2,2)
            Debug.Print idxRow, idxCol, arr2(idxRow, idxCol)
        Next idxCol
    Next idxRow

End Sub
' 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