首页 > 解决方案 > 从多个工作表中删除行

问题描述

我已经在网上冲浪了一段时间,如果它们包含关键字,我一生都无法弄清楚如何从同一工作簿中的多个工作表中删除行。

表 1(总体)包含所有数据,以下 5 个表(QB、RB、WR、DEF、K)包含表 1(总体)的部分数据。

我想要完成的是搜索一个名称(例如 Aaron Rodgers)并从包含该引用的所有工作表中删除所有行(因此在上面的示例中,Aaron Rodgers 行将从整体QB 中删除,因为他的名字会出现在这两张纸上)。

名称搜索将始终在变化,因此它是一种搜索并销毁包含我从所有工作表中选择的参考名称的行。

标签: excel

解决方案


你需要:

  1. 定义搜索字符串
  2. 定义父工作簿
  3. 循环浏览该工作簿中的选定工作表
  4. 找到包含搜索字符串的行并删除它们

代码:

Option Explicit

Sub destroy()
    Dim str As String, w As Long, m As Variant, wss As Variant

    wss = Array("Overall", "QB", "RB", "WR", "DEF", "K")

    '1. define the search string
    str = Application.InputBox(prompt:="search for:", Title:="search and destroy", _
                             Default:="Aaron Rodgers", Type:=xlTextValues)

    If CBool(Len(str)) And str <> "False" Then

        '2. define the parent workbook
        With ThisWorkbook

            '3. loop through selected worksheets within that workbook
            For w = LBound(wss) To UBound(wss)
                With .Worksheets(wss(w))

                    '4. locate rows containing the search string and delete them
                    m = Application.Match(str, .Columns(1), 0)
                    Do While Not IsError(m)
                        .Cells(m, "A").EntireRow.Delete
                        m = Application.Match(str, .Columns(1), 0)
                    Loop

                End With
            Next w

        End With

    End If
End Sub

推荐阅读