我正在努力学习这个课程。在其中,我需要使用看起来像数组的二维数组(表中的#行,2)。出于某种原因,即使我可以正确获取行数,我仍然会收到编译错误:需要常量表达式。
如果有人能给我任何帮助,我们将不胜感激。我不能只为它分配一个静态数字,因为随着时间的推移,表总是会增加,而且我知道一旦数组构建完就无法调整数组的大小。
这是我的代码,如果它能提供任何帮助。
Sub arrayToTest()
Dim rng As Range, row As Range, cell As Range, RowCount As Long, rowsinTable As Integer
Set rng = Sheets("Sheet1").Range("TestTable")
rowsinTable = rng.Rows.Count
Dim arrayTest(rowsinTable, 2) As String
RowCount = 1
For Each row In rng.Rows
arrayTest(RowCount - 1, 0) = rng.Cells(RowCount, 2)
RowCount = RowCount + 1
Next row
End Sub
我使用的测试表有3行。
答案 0 :(得分:2)
Sub arrayToTest()
Dim rng As Range, row As Range, cell As Range, RowCount As Long, rowsinTable As Integer
Dim arrayTest() As String 'First Declare the array
Set rng = Sheets("Sheet1").Range("TestTable")
rowsinTable = rng.Rows.Count
ReDim arrayTest(rowsinTable, 2) As String 'Then Re-Declare it to size.
RowCount = 1
For Each row In rng.Rows
arrayTest(RowCount - 1, 0) = rng.Cells(RowCount, 2)
RowCount = RowCount + 1
Next row
End Sub