Excel VBA 中的 for 循环

3

我正在尝试在 Excel 列上使用 For 循环。这是我的代码:

   For Each c In Worksheets("sheet1").Range("A1:A5000").Cells
        c.Offset(0, 1).Range("A1").Value = Right((Left(c, 13)), 7)
   Next

它可以正常工作,问题出在

Range("A1:A5000")

我的表格行数不到1000行,但是它可能会增长,我希望能够仅对有数据的行使用循环。如何将其更改为从A1到最后一个非空行?


请查看https://dev59.com/E3VD5IYBdhLWcg3wBW3d。 - GSerg
在循环内,你的.Range("A1")是多余的。 - Tim Williams
http://stackoverflow.com/questions/15770574/how-to-count-non-empty-cells-in-macro/15771514#15771514 - Zhenya
2个回答

2
Dim RowIndex As Long
RowIndex = 1

Dim c

While Not IsEmpty(Worksheets("sheet1").Cells(RowIndex, 1))
    Set c = Worksheets("sheet1").Cells(RowIndex, 1)
    c.Offset(0, 1).Range("A1").Value = Right((Left(c, 13)), 7)
    RowIndex = RowIndex + 1
Wend

1

你可以尝试这个...

Dim r As Range

Set r = Range("A65536").End(xlup)

For Each c In Worksheets("sheet1").Range("A1:" & r.Address).Cells
   c.Offset(0, 1).Range("A1").Value = Right((Left(c, 13)), 7)
Next

3
应该将代码改为 Set r = Cells(Rows.Count,"A").End(xlup) 来处理 Excel 2007 及以上版本 - 当前的公式适用于 Excel 2003 及更早的版本,但现在有更多的行。 - brettdj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接