excel - vba - 循环通过 3 列

标签 excel for-loop vba

我的excel有4列。

对于 A 列中的每个元素,我想遍历 C 列中的每个元素。如果 C 列中的元素等于 A 列,则它返回 B 列中 D 列的值。

例如,B4 应该返回“dog”。 B5 应该返回“鸡蛋”。 B6 应该返回“猫”。

enter image description here

enter image description here

我运行了我的 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

最佳答案

只是那里有太多的循环。它实际上是在正确地找到第一个值,并将其放入“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

关于excel - vba - 循环通过 3 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29882245/

相关文章:

excel - Access VBA - XLS 后期绑定(bind),未找到变量

javascript - 我可以在循环中更改索引吗?

vba - IF 语句中的 "And"和 "Or"问题

python - 如何在python上用pywinauto打开一个excel文件?

excel - AutoFiltered 数据的 VLOOKUP 宏

ruby-on-rails - Ruby on Rails 中的 send_data 与电子表格插件结合使用时遇到困难

java - for循环中的Findviewbyid()

java - 为什么我的程序不考虑将用户输入的值相加?

Excel VBA,Worksheet.Change 为 3 个单元格

excel - 将内容从单元格移动到带有空格的 msgbox?