VBA – ReDim保留创buildfalse数组元素
这是for循环来查找范围内的值,并创build新的数组充满匹配结果。 问题是查看我在第一个看到的对象如果语句AR2(i)创build一个为空的元素AR2(0),则将AR2(1)指定为If Else值。
Sub rt() Dim AR0() As Variant, AR1() As Variant, AR2() As Variant Dim WS0 As Worksheet, WS1 As Worksheet Dim i As Integer, RW0 As Integer, RW1 As Integer Dim C As Range Set WS0 = Sheets("lookup") Set WS1 = Sheets("centro") RW1 = WS1.Cells(WS1.Rows.Count, "A").End(xlUp).row AR0 = WS0.Range("A3:A28") For i = 1 To UBound(AR0, 1) With WS1.Range("A2:A" & RW1) Set C = .find(AR0(i, 1), LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext) ReDim Preserve AR2(i) If Not C Is Nothing Then AR2(i) = "YES" Else AR2(i) = " - " End If End With Next WS0.Range("B3:B28") = WorksheetFunction.Transpose(AR2) End Sub
AR2创build元素AR2(0)时没有分配赋值错误。 解决方法是将For循环从0和AR0(i + 1,1)开始,以允许从循环位置0开始查找该值。谢谢!
Sub rt() Dim AR0() As Variant, AR1() As Variant, AR2() As Variant Dim WS0 As Worksheet, WS1 As Worksheet Dim i As Integer, RW0 As Integer, RW1 As Integer Dim C As Range Set WS0 = Sheets("lookup") Set WS1 = Sheets("centro") RW1 = WS1.Cells(WS1.Rows.Count, "A").End(xlUp).row AR0 = WS0.Range("A3:A28") For i = 0 To UBound(AR0, 1) - 1 With WS1.Range("A2:A" & RW1) Set C = .find(AR0(i + 1, 1), LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext) ReDim Preserve AR2(i) If Not C Is Nothing Then AR2(i) = "YES" Else AR2(i) = " - " End If End With Next WS0.Range("B3:B28") = WorksheetFunction.Transpose(AR2) End Sub