vba 每个循环的excel vba一次需要2个步骤

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1120523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 10:35:27  来源:igfitidea点击:

excel vba for each loop takes 2 steps at once

excel-vbafor-loopforeachvbaexcel

提问by Roman Glass

I want to process every element of a for-loop. Taking this code, why is just every second element processed?

我想处理 for 循环的每个元素。以这段代码为例,为什么只处理第二个元素?

For Each row In ws.Rows
    If IsEmpty(row.Cells(row.row, 1)) Then
        Exit For
    Else
        MsgBox row.Cells(row.row, 1).value
    End If
Next

Thanks in advance for your answers!

提前感谢您的回答!

回答by Zyphrax

Instead of refering to Row.Cells refer to Worksheet.Cells. Also, you might want to select the ActiveRange of the worksheet, that should prevent a lot of useless Rows in your for-each.

而不是指 Row.Cells 指的是 Worksheet.Cells。此外,您可能想要选择工作表的 ActiveRange,这应该可以防止 for-each 中出现大量无用的行。

Check out MSDN for examples on this.

有关这方面的示例,请查看 MSDN。

回答by amarcy

Setting ws to a Range with the range of cells B1:B10 which contain the values 1-10 respectively will produce the desired result:

将 ws 设置为单元格范围为 B1:B10 的范围,分别包含值 1-10 将产生所需的结果:

Sub Macro1() Dim ws As Range

Sub Macro1() Dim ws As Range

Set ws = Range("B1:B10")

设置 ws = Range("B1:B10")

For Each Row In ws.Rows

对于 ws.Rows 中的每一行

If IsEmpty(ws.Cells(Row.Row, 1)) Then
    Exit For
Else
    MsgBox ws.Cells(Row.Row, 1).Value
End If

Next

下一个

End Sub

结束子