我的Excel上有4列。
对于A列中的每个元素,我想循环遍历每个元素列C.如果C列中的元素等于A列,则它返回B列中D列的值。
例如,B4应该返回" dog"。 B5应该返回" egg"。 B6应该返回" cat"。
我运行了我的VBA代码。 B列中的所有值都返回" egg"。有人可以查看我的以下VBA代码吗?
Sub testing_click()
Dim x As Variant
Dim arr1 As Variant
Dim i , r As Long
arr1 = Worksheets("testing").Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row).Value
For Each x In arr1
For r = 1 To 5
If x = Trim(Worksheets("testing").Cells(r, "c").Value) Then
For i = 1 To Worksheets("testing").Range("a1048576").End(xlUp).Row
Worksheets("testing").Cells(i, "b").Value = Worksheets("testing").Cells(r, "d").Value
Next i
End If
Next r
Next x
End Sub
答案 0 :(得分:2)
arr1必须是Dim'如数组... Dim arr1() As Variant
我还建议用更多类似VBA的循环结构替换End(xlUpDownLeftRightHomeEnd)
,例如。
Sub ClassicalLoops()
Dim OuterLoop As Integer, InnerLoop As Integer
Dim DataRange As Range, LookupRange As Range
Set DataRange = [A1]
Set LookupRange = [C1]
OuterLoop = 1
Do While DataRange(OuterLoop, 1) <> ""
InnerLoop = 1
Do While LookupRange(InnerLoop, 1) <> ""
If DataRange(OuterLoop, 1) = LookupRange(InnerLoop, 1) Then
DataRange(OuterLoop, 2) = LookupRange(InnerLoop, 2)
Exit Do
Else
InnerLoop = InnerLoop + 1
End If
Loop
OuterLoop = OuterLoop + 1
Loop
End Sub
答案 1 :(得分:2)
那里只有一个太多的循环。它实际上做的是正确地找到第一个值,并将它放在列“B”的所有12行中。然后找到第二个值,并重新分配列“B”的所有12行。
摆脱最里面的循环,在同名的地方添加计数器,你就可以了。现在,不是查看“A”列中的所有单元格,而是只查看填充的单元格,并在匹配时立即终止内部循环。
还纠正了声明中的错误。 Dim i, r As Long
实际上只会r
长,i
为变体。 Dim i as Long, r as Long
会将它们捕获为Long类型。
希望它有所帮助!
Sub testing_click()
Dim x As Variant
Dim arr1 As Variant
Dim i as Long, r As Long
arr1 = Worksheets("testing").Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row).Value
'initialize row counter out here
i = 1
For Each x In arr1
For r = 1 To 5
If x = Trim(Worksheets("testing").Cells(r, "c").Value) Then
Worksheets("testing").Cells(i, "b").Value = Worksheets("testing").Cells(r, "d").Value
'Increment row counter and exit inner loop
i = i + 1
Exit For
End If
Next r
Next x
End Sub