简体   繁体   中英

How can I write Excel VBA code to repeat until it reaches the worksheet edge?

I'd like to write some VBA that performs an action repeatedly on cells until it reaches the worksheet edge, eg column A, no matter where it started from. I've found that if I tell it to repeat more times than there are columns I get an error as the code tries to move to a column to the left of column A. How can I limit a loop to stop at column A?

For example, if I use

 For n = 1 To 5
'
ActiveCell.Offset(0, -1).Range("A1:A2").Select
Selection.merge

'
Next n

Then if I start this with a cell in column G selected it's OK, but if I had a cell in column F or less selected, it crashes.

Thanks!

This should do what you want. Note that a key principal of VBA is that there's almost never a need to Select cells. (Although the macro recorder doesn't know that).

Sub MergeEm()
Dim n As Long
Dim cellActive As Excel.Range
Dim CellRow As Long

Set cellActive = ActiveCell
CellRow = cellActive.Row
'Stepping backwards - not necessary, but in spirit with your original code
For n = cellActive.Column To 1 Step -1
    cellActive.Parent.Cells(CellRow, n).Range("A1:A2").Merge
Next n
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM