对于每个编译错误(多个范围)

时间:2018-05-03 16:40:12

标签: excel vba excel-vba for-loop

全部,

我确信有一个快速的答案然而这让我感到沮丧,因为这个问题非常基本,所以我很抱歉。

我有一个For Each循环,我需要迭代几次,但是当我键入两个以上的范围来迭代屏幕截图时会显示错误。

    Dim TargetCell As Range, ICol As Integer
    Set TargetCell = Rows("9").Find(What:="Forecast", LookIn:=xlValues, LookAt:=xlPart)
    If Not TargetCell Is Nothing Then ICol = TargetCell.Column



For Each c In Range(Cells(12, ICol), Cells(18, 73), Cells(19, ICol), Cells(42, 73), Cells(47, ICol), Cells(53, 73), Cells(55, ICol), Cells(76, 73))

非常感谢任何有关错误的帮助

编译错误消息:
enter image description here

***** UPDATE

我已将代码更新为工会,这已经解决了论坛帮助的问题 请参阅下面的新代码;

Dim Rng1, Rng2, Rng3, Rng4 As Range

Set Rng1 = Range(Cells(12, ICol), Cells(18, 73))
Set Rng2 = Range(Cells(19, ICol), Cells(42, 73))
Set Rng3 = Range(Cells(47, ICol), Cells(53, 73))
Set Rng4 = Range(Cells(55, ICol), Cells(76, 73))

 Dim C as variant
    For Each c In Union(Rng1, Rng2, Rng3, Rng4)

发布答案以供将来参考

1 个答案:

答案 0 :(得分:1)

有很多方法可以制作一个细胞循环。正如评论中所提到的,Range.Union确实是一个好主意。另一个是将所有单元格放在一个数组中并像这样循环遍历它们:

Option Explicit

Public Sub TestMe()

    Dim c As Variant
    Dim Icol As Long:    Icol = 5

    For Each c In Array(Cells(12, Icol), Cells(18, 73), Cells(19, Icol), Cells(42, 73))
        Debug.Print c.Address
        c.Interior.Color = vbRed
    Next c

End Sub