vba Excel - 将单元格的内容乘以 12,仅一次
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13843089/
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
Excel - Multiply contents of cell by 12, only once
提问by Jeremy1026
I am trying to update values entered into cells in Column A
. I have the following script which works as expected, almost. It updates the cell, but then continues to update until it reaches an exponentially large number.
我正在尝试更新输入到Column A
. 我有以下脚本,几乎可以按预期工作。它更新单元格,然后继续更新,直到达到指数级大数。
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 1 Then
intcolumn = Target.Column
introw = Target.Row
Cells(introw, intcolumn) = Cells(introw, intcolumn) * "12"
End If
End Sub
Is there a way to make it so that I can make it so I can enter any number in A? and have it only multiply by 12 once? (1 = 12, 2 = 24, 3 = 36, 4 = 48, etc.)
有没有办法做到这一点,以便我可以做到这样我就可以在A中输入任何数字?并且只乘以 12 一次?(1 = 12, 2 = 24, 3 = 36, 4 = 48, 等等)
回答by martin
Your change is triggering the Worksheet_Change event again. You need to have some kind of flag to keep track of it:
您的更改再次触发 Worksheet_Change 事件。您需要有某种标志来跟踪它:
Private changeFlag As Boolean
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 1 And Not changeFlag Then
changeFlag = True
intcolumn = Target.Column
introw = Target.Row
Cells(introw, intcolumn).Value = Cells(introw, intcolumn).Value * 12
Else
changeFlag = False
End If
End Sub
回答by David Zemens
Multiplying the cell value triggers the Worksheet_Change
event, which is triggering this macro. So, when you enter "1" in to cell A1, this is a change that causes multiplication 1*12=12, but thisis also a change, which causes 12*12=144, which is also a change, etc., which is why it's repeating.
将单元格值相乘会触发Worksheet_Change
事件,即触发此宏。所以,当你为“1”,在单元格A1进入,这是导致乘法1 * 12 = 12的改变,而这也是一个变化,这将导致12 * 12 = 144,这也是一个变化,等等,这就是它重复的原因。
This should fix it, disable events before performing the operation, then re-enable events before exiting the subroutine:
这应该修复它,在执行操作之前禁用事件,然后在退出子例程之前重新启用事件:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 1 Then
Application.EnableEvents = False 'Prevent looping based on the 'change' caused by multiplication
intcolumn = Target.Column
introw = Target.Row
Cells(introw, intcolumn) = Cells(introw, intcolumn) * "12"
Application.EnableEvents = True 'allow events again
End If
End Sub