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

VBA代码仅在首个工作表生效,多表循环删除行失败求助

解决遍历多工作表删除行失效的VBA问题

嘿,我一眼就看出问题出在哪了——你单工作表运行正常,但遍历所有表时失效,核心原因是没有给Range和Rows指定明确的工作表对象,导致代码始终在当前活动的工作表上操作,根本没碰循环到的其他工作表!

修正后的代码

Sub myDeleteRows()
    Dim lRow As Long
    Dim i As Integer
    Dim core_cities As Variant
    Dim sh As Worksheet
    
    core_cities = Array("Bristol", "Birmingham", "Cardiff", "Leeds", "Liverpool", "Manchester", "Newcastle-upon-Tyne", "Nottingham", "Sheffield")
    
    For Each sh In ActiveWorkbook.Sheets
        ' 动态获取当前工作表A列的实际最后一行(替代固定的140,更灵活)
        lRow = sh.Cells(sh.Rows.Count, "A").End(xlUp).Row
        ' 从最后一行往上遍历(避免删除行后索引错乱)
        For i = lRow To 4 Step -1
            ' 关键:所有单元格/行操作都绑定到当前循环的sh工作表
            If IsError(Application.Match(sh.Range("A" & i).Value, core_cities, False)) Then
                sh.Rows(i).Delete
            End If
        Next i
    Next sh
    
    MsgBox ("complete")
End Sub

关键修改说明

  1. 绑定工作表对象:把原来的Range("A" & i)改成sh.Range("A" & i),Rows(i)改成sh.Rows(i)。这一步是核心,确保每一次循环都精准操作当前的sh工作表,而不是默认的活动表。
  2. 动态获取最后一行:替换了固定的lRow = 140,改成自动读取每个工作表A列的实际数据行,避免因不同工作表数据行数不同导致遗漏或处理空行。

额外优化建议(可选)

如果你的工作表数据量较大,建议加上屏幕刷新关闭,提升运行速度:

Sub myDeleteRows_optimized()
    Dim lRow As Long
    Dim i As Integer
    Dim core_cities As Variant
    Dim sh As Worksheet
    
    core_cities = Array("Bristol", "Birmingham", "Cardiff", "Leeds", "Liverpool", "Manchester", "Newcastle-upon-Tyne", "Nottingham", "Sheffield")
    
    ' 关闭屏幕刷新,避免频繁闪烁,加速运行
    Application.ScreenUpdating = False
    
    For Each sh In ActiveWorkbook.Sheets
        lRow = sh.Cells(sh.Rows.Count, "A").End(xlUp).Row
        For i = lRow To 4 Step -1
            If IsError(Application.Match(sh.Range("A" & i).Value, core_cities, False)) Then
                sh.Rows(i).Delete
            End If
        Next i
    Next sh
    
    ' 恢复屏幕刷新
    Application.ScreenUpdating = True
    MsgBox ("complete")
End Sub

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:28:25