使用Range.Find()时出现“对象变量或With块变量未设置”错误求助
VBA Range.Find 报错“对象变量或With块变量未设置”的解决方法
错误原因
- Find方法未匹配到值:当
Range.Find()搜索不到目标内容时,会返回Nothing,此时直接调用.Activate就会触发该错误。 - ListBox索引无效:如果ListBox未选中任何项,
ListIndex的值为-1,此时访问Me.ListBox1.List(Me.ListBox1.ListIndex, 0)会触发索引越界,间接引发后续报错。
修复方案及代码
- 先校验ListBox的选中状态,避免无效索引访问
- 将Find结果赋值给独立Range变量,判断找到后再执行后续操作
- 摒弃
Activate/ActiveCell依赖,直接通过变量操作单元格,提升代码稳定性
修正后的代码:
Dim ws As Worksheet Dim sear As String Dim Rng2 As Range Dim foundCell As Range ' 存储Find结果的变量 Set rng = ThisWorkbook.Sheets("ORDER").Range("B2:B1000000") Set Rng3 = ThisWorkbook.Sheets("CONVERSION_DB").Range("G2:G1000000") Me.Label22 = Me.TextBox1.Value Me.Label23 = Me.TextBox2.Value ' 检查ListBox是否有选中项 If Me.ListBox1.ListIndex >= 0 Then Me.Label24 = Me.ListBox1.List(Me.ListBox1.ListIndex, 0) Me.Label25 = Me.ListBox1.List(Me.ListBox1.ListIndex, 1) ' 统计匹配数量 Dim MyCount As Long Set ws = ThisWorkbook.Sheets("CORRUGATE_DB") MyCount = Application.CountIf(ws.Range("BE2:BE1000000"), TextBox1.Value & Me.ListBox1.List(Me.ListBox1.ListIndex, 0)) Me.TextBox3.Value = MyCount Application.ScreenUpdating = False ' 执行查找操作 Set Rng2 = ws.Range("BE2:BE1000000") sear = CStr(Me.TextBox1.Value & Me.ListBox1.List(Me.ListBox1.ListIndex, 0)) Set foundCell = Rng2.Find(What:=sear, After:=ws.Range("BE2"), LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) ' 找到匹配项后累加对应值 If Not foundCell Is Nothing Then Me.TextBox4.Value = Me.TextBox4.Value + foundCell.Offset(0, -30).Value End If Application.ScreenUpdating = True Else MsgBox "请在ListBox中选择一项" End If
额外提示
- 减少
Activate和ActiveCell的使用,直接通过工作表、单元格变量操作,可避免因激活状态变化导致的意外错误 - 使用
Find方法后,必须先判断返回值是否为Nothing,这是VBA处理查找操作的标准规范
内容的提问来源于stack exchange,提问作者Ace99
相关产品推荐
相关产品推荐

