Inputbox停止接受鼠标select在Excel VBA中的每个循环,因为screenupdating更改在另一个子 – 为什么?

为什么一个input框会在调用variablesscreenupdating的子调用后停止接受鼠标的select?

我有一个Excel中的大型工作簿,可以从不同的工作表上的不同组件计算预算。 我在所有公式中都使用了命名范围,而且在构build工作簿时,我经常需要在表单上移动东西,因此编辑引用到我命名的范围,所以我创build了一个macros来运行我的命名范围,让我点击更新他们的参考。

我已经包含了我的工作簿代码中的三个子集; 工作表1只在命名范围单元格中有一些值,一个公式(= CNGFixedCost1 + CNGFixedCost2 + CNGFixedCost3)和一个activexcheckbox。 当我运行RangeNameManager()input框停止接受鼠标select,由于在Worksheet_Calculate()子,screenupdatingvariables。 我想出了如何解决这个问题(删除screenupdating变化),但我仍然好奇,为什么会发生这种情况。

Option Explicit 'Name Ranges in workbook Public Sub Workbook_Open() Worksheets("Sheet1").Range("D3").Name = "CNGFixedCost1" Worksheets("Sheet1").Range("D4").Name = "CNGFixedCost2" Worksheets("Sheet1").Range("D5").Name = "CNGFixedCost3" End Sub 'Update named ranges Sub RangeNameManager() Dim nm As Name Dim nms As String Dim xTitleID As String Dim InputRng As Range Dim asnms As String On Error Resume Next asnms = CStr(ActiveSheet.Name) For Each nm In ActiveWorkbook.Names nms = CStr(nm.Name) If nm.RefersTo Like "*" & asnms & "*" Then Set InputRng = ActiveSheet.Range("A1") Set InputRng = Application.InputBox("The current range for" & nms & " is " & CStr(nm.RefersTo) & ". Select the new range.", InputRng.Address, Type:=8) nm.RefersTo = InputRng End If Next On Error GoTo 0 End Sub ' Update check box automatically Private Sub Worksheet_Calculate() Application.ScreenUpdating = False '***Removed to resolve problem.*** Dim errwksht As String errwksht = ActiveSheet.Name On Error GoTo ErrorHandler If Worksheets("Sheet1").Range("CNGFixedCost1").Value > 0 Then Worksheets("Sheet1").CheckBox1.Value = False Else Worksheets("Sheet1").CheckBox1.Value = True End If ErrorHandler: Exit Sub Application.ScreenUpdating = True '***Removed to resolve problem.*** End Sub 

在重新启动屏幕更新之前,您正在退出子组,导致应用程序处于不稳定状态。

 ' Update check box automatically Private Sub Worksheet_Calculate() Application.ScreenUpdating = False '***Removed to resolve problem.*** '... ErrorHandler: Exit Sub 'exits here Application.ScreenUpdating = True ' so this NEVER executes End Sub 

这很容易通过在你的error handling程序中恢复,这将更好地命名为CleanExit: 这是我将如何写它。

 Private Sub Worksheet_Calculate() On Error GoTo ErrorHandler Application.ScreenUpdating = False '***Removed to resolve problem.*** '... CleanExit: Application.ScreenUpdating = True Exit Sub ErrorHandler: ' Actually do some error handling Resume CleanExit End Sub 

ScreenUpdating是Application对象的一个​​属性。 如果将其设置为false,则应用程序将切断与用户的连接(不会进行input,也不会更新显示)。

如果你想让某些东西运行得更快,这是非常有用的,但是在你需要用户交互的时候不应该使用它。