[英]Run-Time Error '9': subscript out of range with WorksheetFunction
I'm trying to write a simple code to look at a data input section and add that data into an existing data table. 我正在尝试编写一个简单的代码来查看数据输入部分,并将该数据添加到现有数据表中。 The number of rows I want to copy changes every time so I attempted to make the array capable of adjusting size to suit.
我想复制的行数每次都会更改,因此我试图使该数组能够调整大小以适应需要。
Dim size As Integer
Dim new_resources() As String
Dim i as Integer
size = worksheetfunction.CountA("E:E") - 1
**ReDim new_resources(size)**
i=1
For i to size
new_resources(i) = cells(i+1,5)
Next i
I get the following error: 我收到以下错误:
Run-time error '9': Subscript out of range.
运行时错误'9':下标超出范围。
on the line marked with **. 在标有**的行上。
数组以0而不是1开头。因此将new_resources(i)更改为new_resources(i-1)。
If you're getting that error on your ReDim
line, it must mean that size
is less than zero, which must mean that COUNTA("E:E")
is returning zero. 如果您在
ReDim
行上遇到该错误,则必须表示size
小于零,这必须表示COUNTA("E:E")
返回零。 You may want to assert that size >= 0
before attempting to ReDim
your array. 您可能要到断言
size >= 0
试图之前ReDim
您的阵列。 For example: 例如:
size = worksheetfunction.CountA("E:E") - 1
If size < 0 Then
MsgBox "Error! No rows found in column E."
Else
ReDim new_resources(size)
End If
That's not how the WorksheetFunction object works. 那不是WorksheetFunction对象的工作方式。 On the worksheet, that is sufficient to pass in a cell range but not in VBA.
在工作表上,这足以在单元格区域中传递,但在VBA中还不够。
Dim sz As Long
Dim new_resources() As String
Dim i as Integer
sz = worksheetfunction.CountA(Range("E:E")) - 1
ReDim new_resources(sz)
i=1
For i to sz
new_resources(i) = cells(i+1, 5)
Next i
'alternates
sz = worksheetfunction.CountA(Columns(5)) - 1
sz = worksheetfunction.CountA(Cells(1, 5).EntireColumn) - 1
You need to reference one or more cells on a worksheet like you do in other VBA operations. 您需要像在其他VBA操作中一样引用工作表上的一个或多个单元格。 The lack of a parent worksheet worries me;
缺少父工作表使我感到担心; maybe you should address that as well.
也许您也应该解决这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.