我是VBA的新手,我需要扩展现有的工作表并保持其格式。有7个部分的长度可变(以行为单位),宽度为14列,需要完成。所以我想做的是以下事情:
我设法完成了第1步,目前在第2步中很挣扎:我需要创建一个长度可变的数组,可以在其中插入数据。
到目前为止,我的代码:
' this should create the array with the 7 entries
' "myArray" contains the row-numbers where the sections start
Function GenerateSheetArray(sheet As Worksheet, myArray As Variant) As Variant
Dim finalArray As Variant
Dim myInt As Integer
'here each entry should be filled
For i = 0 To 6
myInt = myArray(i)
finalArray(i) = GenerateArrayPart(sheet, myInt)
Next
GenerateSheetArray = finalArray
End Function
'This should fill each entry with the data of corresponding section
Function GenerateArrayPart(sheet As Worksheet, headline As Integer) As Variant
Dim leftIndex As Integer, rightIndex As Integer, rowcount As Integer
Dim sheetArray() As Variant
rowcount = 0
leftIndex = 1
rightIndex = 14
i = headline + 1
Do While sheet.Cells(i, 1) <> ""
rowcount = rowcount + 1
i = i + 1
Loop
If (rowcount > 0) Then
For colIndex = leftIndex To rightIndex
For rowIndex = 1 To rowcount
Row = headline + rowIndex
sheetArray(rowIndex - 1, colIndex - 1) = sheet.Cells(Row, colIndex)
Next
Next
End If
GenerateArrayPart = sheetArray
End Function
现在我的问题是,VBA在此行引发错误:
'atm rowIndex and colIndex are 1, Row is 40
'I know that there is data in that cell
sheetArray(rowIndex - 1, colIndex - 1) = sheet.Cells(Row, colIndex)
VBA说:
索引超出范围
在方法GenerateArrayPart
中。
怎么会这样我认为variant
几乎可以包含所有内容,也不需要使用界限吗?
答案 0 :(得分:2)
您在数组中没有任何值。因此,仅声明数组,而未定义维度。
尝试一下:
Dim finalArray As Variant
Redim finalArray(6)
现在,数组内部将有7个值。从0到6。在Function GenerateArrayPart
中,数组sheetArray
发生相同的错误。在那里,您需要将数组声明为多维数组。例如。 Redim sheetArray (N, M)
。
要查看一些小的工作示例,请看下面的代码:
Sub TestMe()
Dim finalArr As Variant
ReDim finalArr(6)
Dim i As Long
For i = LBound(finalArr) To UBound(finalArr)
finalArr = GenerateArrPart(i)
Next i
For i = LBound(finalArr) To UBound(finalArr)
Debug.Print i; finalArr(i, i)
Next i
End Sub
Public Function GenerateArrPart(a As Long) As Variant
Dim i As Long
Dim arrReturn As Variant
ReDim arrReturn(a + 1, a + 1)
For i = LBound(arrReturn) To UBound(arrReturn)
arrReturn(i, i) = a * i
Next i
GenerateArrPart = arrReturn
End Function
这是输出:
0 0
1 6
2 12
3 18
4 24
5 30
6 36
7 42