0

我正在用 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

错误如下:

在此处输入图像描述

4

3 回答 3

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
于 2021-06-20T06:33:14.147 回答
0

我认为系统需要您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

于 2021-06-20T04:51:56.237 回答
0

您可以将范围中的值直接放入数组中,然后在循环中使用LBoundandUBound来获取每个维度的下限/上限。

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
于 2021-06-20T05:06:25.313 回答