简体   繁体   English

如何编写Excel VBA代码以重复直到到达工作表边缘?

[英]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. 我想编写一些VBA,无论它从何处开始,它都会反复对单元格执行操作,直到到达工作表边缘(例如A列)为止。 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? 我发现,如果我告诉它重复的次数多于列数,则在代码尝试移至A列左侧的列时会出现错误。如何限制循环以在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. 然后,如果我从选中的G列中的一个单元格开始就可以了,但是如果我在F列或更少的列中选择了一个单元格,它就会崩溃。

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. 请注意,VBA的关键原理是几乎不需要Select单元格。 (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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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