在VBA For循环中使用两个以上的范围

时间:2014-03-01 00:20:49

标签: excel vba excel-vba

所以我正在尝试使用For循环在Excel中的三个单独列中执行操作。

Sub dostuff()
  Dim lRw As Long, C As Range

  ' Get number of active rows by finding last row index.
  lRw = Range("A" & Rows.Count).End(xlUp).Row

  For Each C In Range("B1:B" & lRw, "H1:H" & lRw)
  ' stuff happens
  Next
End Sub

当我仅指定一个或两个列范围时,这可以正常工作,但是当我尝试添加第三个时,它会失败:

For Each C In Range("B1:B" & lRw, "H1:H" & lRw, "M1:M" & lRw)

有没有办法迭代三列(或更多)而不只是两列?

2 个答案:

答案 0 :(得分:3)

在你进行循环之前,只需要一个联盟来组合你的范围

Dim loopRange as Range
Set loopRange = Union(Range("B1:B" & lRw),Range("H1:H" & lRw),Range("M1:M" & lRw))
For Each C In loopRange
    'stuff
Next C

答案 1 :(得分:3)

Sub Tester()
Dim c As Range, lRw As Long

    lRw = 5
    For Each c In Range("B1:B" & lRw & ",H1:H" & lRw & ",M1:M" & lRw).Cells
        Debug.Print c.Address(False, False)
    Next c

End Sub