【发布时间】:2019-01-25 00:17:39
【问题描述】:
我正在尝试创建一个数组,从 UBound 循环到 LBound 并使用以下代码检查值。
我在线收到错误消息:
If arrPart(i) = strResult Then
运行时错误 9
我尝试在数组中导入的范围:
代码:
Option Explicit
Sub ArrayTest()
Dim LastColumn As Long, CounterPart As Long, i As Long
Dim arrPart As Variant
Dim strResult As String
With ThisWorkbook.Worksheets("Sheet1")
LastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
strResult = "N"
'Set as an array the 4 last matches
arrPart = .Range(Cells(1, LastColumn - 3), Cells(1, LastColumn))
CounterPart = 0
For i = UBound(arrPart) To LBound(arrPart) Step -1
If arrPart(i) = strResult Then
CounterPart = CounterPart + 1
Else
Exit For
End If
Next
End With
End Sub
有什么建议吗?
【问题讨论】:
-
arrPart是一个二维数组,必须像arrPart(row, column)一样使用。您可以将UBound(arrPart, 1)用于row,将UBound(arrPart, 2)用于column。 -
If arrPart(1,i) = strResult Then还要确保将父级附加到Range()内的Cells(),否则如果该工作表不是活动工作表,则会出现错误:arrPart = .Range(.Cells(1, LastColumn - 3), .Cells(1, LastColumn)) -
您还可以对数组进行双重转置以获得一维数组
WorksheetFunction.Transpose(WorksheetFunction.Transpose(.Range(.Cells(1, LastColumn - 3), .Cells(1, LastColumn)))) -
您可能需要查看以下帖子:stackoverflow.com/questions/26644231/…