开发者

VBA how to loop through a column in Excel

开发者 https://www.devze.com 2023-04-06 11:44 出处:网络
I know start cell, and I need to go down through the column. And I need to exi开发者_JAVA百科t cycle when the next cell is empty. How to do it in VBA code?

I know start cell, and I need to go down through the column. And I need to exi开发者_JAVA百科t cycle when the next cell is empty. How to do it in VBA code?

Thanks for replies


How about;

'//get a range from anchor cell (a1) to the 1st empty cell in the same column;
dim r As Range, cell as Range
set r = Range(Range("A1"), Range("A1").End(xlDown))

'//loop it
for Each cell In r
    msgbox cell.Value
next


I adjusted AlexK's answer:

dim c As Range

'//loop it
for Each c In Range(Range("A1"), Range("A1").End(xlDown))
    msgbox c.Value
next


In VBA, everything cell-based can be done with ranges, using offsets to return the value you are looking for:

Dim Anchor as Range

Set Anchor = Range("A1")

i = 0
Do 
  ' Cell in column is Anchor.Offset(0, i)
  ' i.e., Anchor.Offset(0, 0) = A1
  '       Anchor.Offset(0, 1) = B1
  '       Anchor.Offset(0, ") = C1
  '       etc.

  ' Do whatever you like with this, here!

  i = i + 1
Loop Until Anchor.Offset(0, i) = ""
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号