Excel VBA,工作表中的代码不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13883255/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 18:49:35  来源:igfitidea点击:

Excel VBA, code in worksheet not working

excelvbaworksheet

提问by user1894469

I have the following code in sheet1 (note - this code is in the wroksheet object, not the workbook object or a module):

我在 sheet1 中有以下代码(注意 - 此代码在工作表对象中,而不是工作簿对象或模块中):

Private Sub Worksheet_Change(ByVal Target As Range)
Dim r As Integer
r = ActiveCell.Row
Cells(r - 1, 7).Value = Now()
ActiveWorkbook.save
End Sub

Can someone tell me why: 1. the ActiveWorkbook.save doesnt work above - it gets stuck in an infinite loop instead; 2. why I cant step throught the code by just pressing F8

有人能告诉我为什么: 1. ActiveWorkbook.save 在上面不起作用 - 它被卡在无限循环中;2. 为什么我不能按 F8 单步执行代码

I tried to put the ActiveWorkbook.save in a separate module and then call that function from the code in the worksheet but that got stuck in an infinite loop as well.

我试图将 ActiveWorkbook.save 放在一个单独的模块中,然后从工作表中的代码中调用该函数,但这也陷入了无限循环。

回答by nutsch

You need to disable events to avoid the infinite loop

您需要禁用事件以避免无限循环

Private Sub Worksheet_Change(ByVal Target As Range)
application.enableevents=false
    Cells(target.row - 1, 7).Value = Now()
application.enableevents=true

ActiveWorkbook.save
End Sub

回答by InContext

The infinite loop is caused because when you update the cell with the current date this is causing a worksheet change event which is calling the event code again. You need to disable events as shown below:

造成无限循环是因为当您使用当前日期更新单元格时,这会导致工作表更改事件再次调用事件代码。您需要禁用事件,如下所示:

Private Sub Worksheet_Change(ByVal Target As Range)

Dim r As Integer
r = ActiveCell.Row

Application.EnableEvents = False    
Cells(r - 1, 7).Value = Now()    
Application.EnableEvents = True    
ActiveWorkbook.Save

End Sub