打开Excel工作簿时ListBox触发‘Method or data member not found’编译错误
问题原因与解决方案
错误触发原因
- 工作簿保存时ListBox1处于选中状态,打开Excel时会自动触发其
Click事件。 - 工作簿加载初期,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
相关产品推荐
相关产品推荐

