Excel / VBA在单步执行代码并正常运行时的行为不同

我有VBA代码,其中包括functionWorksheet_Calculate()Worksheet_Change(ByVal Target As Range)因为我想要更新某些单元格时发生任何重新计算,以及当我修改表中的某些特定的单元格。 这两个子程序调用完全相同的子程序。 但是,其中一个工作正常(Worksheet_Change)和另一个(Worksheet_Calculate)不,即使他们都调用完全相同的function。

我采取的下一步是在发生重新计算的地方设置了断点,令我惊讶的是,这次Worksheet_Calculate()执行的代码正常工作(当使用断点逐步执行代码时,等等)。 此外,即使在正常模式(不是在debugging模式下),它也会正常工作,但这是非常随机的。 我不知道是什么原因造成的。 下面是我的潜艇的缩短版本( MakeVisibleUpdateBaselineUpdateDerivative1 …都是我以后定义的所有子例程):

 Private Sub Worksheet_Calculate() MakeVisible UpdateBaseline If ([F4] > 0) Then UpdateDerivative1 End If If ([F4] > 1) Then UpdateDerivative2 End If If ([F4] > 2) Then UpdateDerivative3 End If If ([F4] > 3) Then UpdateDerivative4 End If End Sub Private Sub Worksheet_Change(ByVal Target As Range) If Not Application.Intersect(Sheets("Main").Range("C7:C61"), Range(Target.Address)) Is Nothing Then MakeVisible UpdateBaseline If ([F4] > 0) Then UpdateDerivative1 End If If ([F4] > 1) Then UpdateDerivative2 End If If ([F4] > 2) Then UpdateDerivative3 End If If ([F4] > 3) Then UpdateDerivative4 End If End If End Sub 

花费了更多的时间debugging之后,我相信由于UpdateBaselineUpdateDerivative1等中的代码实际上正在resize和移动一些形状对象(如星形,直线连接器等),并且这些对象会移动到错误即使我用来定位它们的variables似乎具有正确的值。 我的直觉告诉我,移动形状或改变属性需要一些计算,可能会导致一些竞争条件,但这只是一个疯狂的猜测,它可能是完全不相关的。

谢谢!

你可以尝试这样的事情

 Dim ignoreEvents As Boolean Private Sub Worksheet_Calculate() If ignoreEvents = True Then Exit Sub ignoreEvents = True ' your code here ignoreEvents = False End Sub Private Sub Worksheet_Change(ByVal Target As Range) If ignoreEvents = True Then Exit Sub ignoreEvents = True ' your code here ignoreEvents = False End Sub 

由于@Slai,我能够确定这个问题。 这个错误的确是由于当前活动表单上的代码依赖性引起的,但是当我为特定的单元格指定了表格(我将[F4]改为[Main!F4]以及所有其他的出现)之后,我仍然无法弄清楚是什么问题,因为我确定我所有的代码专门用于[Main!<Cell>]Sheets("Main").Range("<Cell>")使当前活动表的依赖消失。 但是,我添加了代码以使Worksheet_Calculate()被触发时,当前活动的工作表返回到“主”,这导致了正确的行为。 我添加的代码是Worksheets("Main").ActivateWorksheet_Calculate()的第一行Worksheets("Main").Activate

谢谢!