Public变量无法传递至Worksheet_SelectionChange的VBA问题
问题原因与解决方案
核心问题
你遇到的AllUpdated始终为False的问题,根源是Public变量的声明位置错误:
- 你把
Public AllUpdated As Boolean写在了ThisWorkbook类模块中,而工作表的Worksheet_SelectionChange事件直接调用AllUpdated时,VBA会默认创建一个未初始化的局部变量(默认值为False),而非引用ThisWorkbook里的那个变量。
两种解决方法
方法1:将Public变量移到标准模块
这是最稳妥的全局变量使用方式:
- 打开VBA编辑器,右键点击项目 -> 插入 -> 模块(新建一个标准模块,比如
Module1) - 在标准模块中声明变量:
Public AllUpdated As Boolean
- 保留
ThisWorkbook和工作表事件的原有代码不变即可,此时所有模块都能正确共享这个变量的值。
方法2:明确引用类模块中的变量
如果不想移动变量,修改工作表事件代码,明确指定引用ThisWorkbook中的AllUpdated:
Private Sub Worksheet_SelectionChange(ByVal Target As Range) Dim MyPicture As Object Dim MyTop As Double Dim MyLeft As Double Dim BottomRightCell As Range Dim r As Long, c As Long ' 补充变量声明,避免隐式变体 Set MyPicture = ActiveSheet.Shapes("OODWatermark") ' 关键修改:明确引用ThisWorkbook中的变量 If ThisWorkbook.AllUpdated Then '- if data is up to date, hide watermark With MyPicture .Visible = False End With Else '- if data is out of date, display watermark '----------------------------------------------------------- '- bottom right cell With ActiveWindow.VisibleRange r = .Rows.Count c = .Columns.Count Set BottomRightCell = .Cells(r, c) End With '------------------------------------------------------------ '- position picture MyTop = BottomRightCell.Top - MyPicture.Height - 5 MyLeft = BottomRightCell.Left - MyPicture.Width - 5 With MyPicture .Visible = True .Top = MyTop .Left = MyLeft End With End If End Sub
额外建议
为了避免刷新失败导致变量值错误,给Workbook_Open添加错误处理:
Sub Workbook_Open() Dim cRefresh As VbMsgBoxResult ' 声明变量类型,避免隐式变体 cRefresh = MsgBox("Would you like to refresh your data?", vbYesNo, "Refresh") If cRefresh = vbYes Then On Error Resume Next Call sRefreshMaster If Err.Number = 0 Then AllUpdated = True Else MsgBox "数据刷新失败:" & Err.Description AllUpdated = False End If On Error GoTo 0 Else AllUpdated = False End If End Sub
内容的提问来源于stack exchange,提问作者The_FACTS_Novice
相关产品推荐
相关产品推荐

