在 Excel-vba 中停止执行直到循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12337700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
stopping a do until loop in Excel-vba
提问by Uttam Paudel
I created this macro to correct an error (to fill blank created by Feb 29 in non-leap years)i have been facing problem in stopping the Do Until loop.
我创建了这个宏来纠正一个错误(填补非闰年 2 月 29 日创建的空白)我在停止执行直到循环时遇到了问题。
the macro does what it is supposed to do but it is not working as supposed to with Do Until ActiveSheet.Cells(3, x) = "2012"
i want it to stop when cell (3,x) is 2012
宏做了它应该做的事情,但它没有按预期工作,Do Until ActiveSheet.Cells(3, x) = "2012"
我希望它在单元格 (3,x) 为 2012 时停止
Sub Feb_CORRECTION()
Dim i, x As Integer
Dim year
Dim leapyear
Range("c64").Select
x = 3
Do Until ActiveSheet.Cells(3, x) = "2012"
year = ActiveSheet.Cells(3, x)
leapyear = year Mod 4
If leapyear > 0 Then
Range(ActiveCell, ActiveCell.End(xlDown)).Select
Selection.Cut
ActiveCell.Offset(-1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(1, 1).Select
Else
ActiveCell.Offset(0, 1).Select
x = x + 1
End If
Loop
End Sub
thank you
谢谢你
回答by Jon Crowell
Your loop is set to exit if the value in row 3 in column x
is "2012".
如果列中第 3 行中的x
值为“2012”,则循环设置为退出。
You initialize x
to 3, then check to see if the year in row 3 is a leap year. You only increment x
if it is, so unless the year in column "C" is a leap year, x
will never get incremented.
您初始化x
为 3,然后检查第 3 行中的年份是否为闰年。x
如果是,你只会增加,所以除非“C”列中的年份是闰年,x
否则永远不会增加。
Try this instead:
试试这个:
Sub Feb_CORRECTION()
Dim i As Integer
Dim x As Integer
Dim year As Integer
Dim leapyear As Integer
Range("c64").Select
x = 3
Do Until ActiveSheet.Cells(3, x) = "2012"
year = ActiveSheet.Cells(3, x)
leapyear = year Mod 4
If leapyear > 0 Then
Range(ActiveCell, ActiveCell.End(xlDown)).Select
Selection.Cut
ActiveCell.Offset(-1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(1, 1).Select
Else
ActiveCell.Offset(0, 1).Select
End If
' increment x regardless of leap year status
x = x + 1
Loop
End Sub
You also have several variables declared as variants, which is a bad idea unless you have a very specific reason for using them. Variants can lead to bugs that are very hard to track down. I've fixed that in the snippet above.
您还有几个变量声明为变体,这是一个坏主意,除非您有使用它们的非常具体的原因。变体可能导致很难追踪的错误。我已经在上面的代码片段中修复了这个问题。
Note that this line in your code is declaring i
as a variant and x
as an integer:
请注意,代码中的这一行声明i
为变体和x
整数:
Dim i, x As Integer
You've also declared both year
and leapyear
as variants. They should probably be integers instead.
您还声明了两者year
和leapyear
作为变体。它们可能应该是整数。
Final comment: format your code with indents. It is much easier to understand what it is doing if formatted correctly.
最后评论:用缩进格式化你的代码。如果格式正确,就更容易理解它在做什么。