You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

打开Excel工作簿时ListBox触发‘Method or data member not found’编译错误

问题原因与解决方案

错误触发原因

  1. 工作簿保存时ListBox1处于选中状态,打开Excel时会自动触发其Click事件。
  2. 工作簿加载初期,ActiveX控件(如ListBox2)或自定义函数FindString尚未完全初始化,导致代码执行时出现“Method or data member not found”编译错误。

解决方法

1. 给ListBox1_Click事件添加初始化判断

修改代码,先确保控件和函数就绪后再执行赋值操作:

Private Sub ListBox1_Click()
    ' 先验证ListBox2已初始化
    If Not Me.ListBox2 Is Nothing Then
        On Error Resume Next
        Dim funcResult As Variant
        funcResult = FindString(Me.ListBox1.Value, "TipoDeProdutos", "Material")
        ' 仅在函数调用无错误时赋值
        If Err.Number = 0 Then
            Me.ListBox2.List = funcResult
        End If
        On Error GoTo 0
    End If
    
    Me.ListBox3.Clear
    Me.ListBox3.ListFillRange = ""
End Sub

2. 阻止工作簿打开时触发控件事件

在ThisWorkbook模块中添加Workbook_Open事件,临时禁用事件并初始化控件状态:

Private Sub Workbook_Open()
    Application.EnableEvents = False
    ' 替换为你的工作表名称,清空ListBox1选中状态避免触发Click
    Me.Worksheets("Sheet1").ListBox1.Value = ""
    Application.EnableEvents = True
End Sub

3. 检查自定义函数的作用域

确保FindString是标准模块中定义的Public函数,而非工作表模块内的Private函数,否则工作表模块在加载初期可能无法访问该函数:

' 标准模块(如Module1)中的代码
Public Function FindString(keyVal As String, sheetName As String, colName As String) As Variant
    ' 你的函数实现代码
End Function

内容的提问来源于stack exchange,提问作者SuavestArt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 13:32:34