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

使用VBA查找匹配行最后一列时遇报错,求解决方案

问题分析与修正代码

错误原因

  • 空引用报错:在判断匹配单元格是否存在前就调用了foundCell.Row,若工作表无匹配值,foundCell为Nothing,此时会触发运行时错误。
  • 单元格定位错误:foundCell.Offset(0, LC)用绝对列号作为相对偏移量,导致取到的并非目标行最后一列的数据。

修正后的代码

Private Sub CommandButton1_Click()
    Dim ws As Worksheet
    Dim searchValue As String
    Dim foundCell As Range
    Dim LR As Long
    Dim LC As Long
    Dim embeddedChart As ChartObject

    searchValue = TextBox1.Text
    
    If searchValue = "" Then Exit Sub

    ' 提前获取Report表初始最后一行,减少循环内重复计算
    LR = Worksheets("Report").Cells(Rows.Count, 1).End(xlUp).Row

    For Each ws In ThisWorkbook.Worksheets
        Set foundCell = ws.Cells.Find(What:=searchValue, LookIn:=xlValues, LookAt:=xlPart)
        
        ' 先确认找到匹配单元格,再执行后续操作
        If Not foundCell Is Nothing Then
            ' 计算匹配行的最后一列列号
            LC = ws.Cells(foundCell.Row, Columns.Count).End(xlToLeft).Column
            
            ' 写入数据到Report表,每次写入后行号递增
            LR = LR + 1
            Worksheets("Report").Range("A" & LR).Value = ws.Name
            Worksheets("Report").Range("B" & LR).Value = foundCell.Offset(0, 1).Value
            ' 直接通过行号+列号定位目标单元格,避免偏移量混淆
            Worksheets("Report").Range("C" & LR).Value = ws.Cells(foundCell.Row, LC).Value
        End If
    Next ws
    
    Call SpecifyAChartType
End Sub

优化说明

  • 把LR的初始计算移到循环外,写入数据后直接递增行号,减少重复调用End(xlUp)的性能开销。
  • 改用ws.Cells(foundCell.Row, LC)直接定位最后一列单元格,避免相对偏移量的逻辑错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 04:20:35