【问题标题】:For Each loop in Excel VBA finishes after only two iterations对于 Excel VBA 中的每个循环仅在两次迭代后完成
【发布时间】:2020-12-29 10:10:55
【问题描述】:

我编写了一个非常小的宏,如果下一列中的单元格为空,它应该在一系列单元格上运行 VLOOKUP 公式。

我的问题是,我运行 For Each 循环并且它正在工作,但在 2 次迭代后宏完成。它应该对每个单元格进行检查。

Sub copyFormula()

Dim i As Long
Dim cell As Variant

i = 4

For Each cell In Sheets

cell = Range("B" & i)

    If Not (IsEmpty(cell)) Then
     Range("C" & i).FormulaR1C1 = "=VLOOKUP(RC[-2],Locations!C[-2]:C[-1],2,FALSE)"
     Else: Range("B" & i).Offset(1, 0).Activate
    End If
    
    i = i + 1
    
Next cell

End Sub

这是工作簿的样子:

【问题讨论】:

  • 这是因为您的cell 代表工作表,而不是单元格。你遍历每张纸。此外,您不希望遍历工作表中的每个单元格。您应该指定要循环的确切范围。
  • 您能否建议,我必须添加或更改什么才能解决此问题 - 指的是工作表而不是单元格?

标签: excel vba for-loop


【解决方案1】:

此代码将遍历B4:B100 范围内激活工作表的每个单元格。如果为空,则将公式添加到列C

Sub copyFormula()

Dim cell As Range

For Each cell In ActiveSheet.Range("B4:B100")
  If Not (IsEmpty(cell)) Then
    cell.Offset(, 1).FormulaR1C1 = "=VLOOKUP(RC[-2],Locations!C[-2]:C[-1],2,FALSE)"
  End If
Next

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-05
    • 2021-07-05
    • 2018-10-23
    • 2015-09-06
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多