首页 > 解决方案 > 工作簿关闭时 ActiveX 复选框上的变量未定义错误

问题描述

我正在用 Excel VBA 开发数据编辑工具。在其中一个工作表上有一个 ActiveX 组合框,用于选择数据行。组合框上的更改事件会根据所选行中的数据更新一系列 ActiveX 复选框。

除了一方面之外,这似乎运行正常。有时当 Excel 工作簿关闭时,关闭操作会触发 checkbox_change 事件。此时编译器检查方法中的所有变量是否已定义并发现复选框不再存在,并给出“编译错误:变量未定义”消息。

更改触发 worksheet_activate 事件(更新用户表单的某些属性)的工作表似乎是控制错误是否发生的原因。

在调试期间使用对象浏览器我可以看到未列出复选框,而它们正在正常执行中。发生错误时的调用堆栈仅包含 checkbox_change 事件。

我已经尝试了一个(有点矫枉过正)在事件处理程序的请求中包含“Exit Sub”的解决方案,但它没有效果 - VBA 仍然想知道当前未定义的变量。

任何有关如何拦截或防止此问题的建议将不胜感激。

这是一个从头开始的示例,我相信它包含工作簿的所有元素,我得到了错误,但在这个示例中没有发生错误 - 我不知道问题的哪个方面丢失了。希望这会有所帮助。

Option Explicit

Private Sub CheckBox1_Click()
    ' apply the checkbox value to the spreadsheet
    Dim rows As Range
    Set rows = Sheet1.Range("RowIDs")

    Dim cell As Range
    For Each cell In rows

        If cell.Value = ComboBox1.Value Then
            cell.Offset(0, 1).Value = CheckBox1.Value
            Exit For
        End If
    Next cell
End Sub

Private Sub ComboBox1_Change()
    ' get the value from the spreadsheet
    ' apply it to the checkbox
    Dim rows As Range
    Set rows = Sheet1.Range("RowIDs")

    Dim cell As Range
    For Each cell In rows
        If cell.Value = ComboBox1.Value Then
            CheckBox1.Value = cell.Offset(0, 1).Value  '<<< This would be the line that causes the error
            Exit For
        End If
    Next cell
End Sub

Private Sub CommandButton1_Click()
    populateCombo
End Sub

Private Sub populateCombo()
    Dim rows As Range
    Set rows = Sheet1.Range("RowIDs")
    ComboBox1.Clear

    ComboBox1.Text = "--- Select row to activate ---"

    Dim cell As Range
    For Each cell In rows
       ComboBox1.AddItem cell.Value
       Next cell
End Sub

Private Sub Worksheet_Activate()
    UserForm1.Label1.Caption = Sheet1.Name
    UserForm1.Show
End Sub

这是控件所在的工作表的屏幕截图

标签: vbaexcelactivex

解决方案


推荐阅读