【问题标题】:Excel VBA delete row based on cellExcel VBA根据单元格删除行
【发布时间】:2017-03-14 10:22:09
【问题描述】:

我有这段代码,我想遍历所有工作表并根据工作表中任何位置的“已完成”值删除整行...这运行但仅在活动工作表上,我想不出一个好方法让它遍历每张纸直到完成......非常感谢任何帮助!太棒了

Private Sub TestDeleteRows()
Dim rFind As Range
Dim rDelete As Range
Dim strSearch As String
Dim sFirstAddress As String

strSearch = "Completed"
Set rDelete = Nothing

Application.ScreenUpdating = False

With Sheet1.Columns("A:AO")
Set rFind = .Find(strSearch, 
LookIn:=xlValues, LookAt:=xlPart,   SearchDirection:=xlNext, MatchCase:=False)
If Not rFind Is Nothing Then
    sFirstAddress = rFind.Address
    Do
        If rDelete Is Nothing Then
            Set rDelete = rFind
        Else
            Set rDelete = Application.Union(rDelete, rFind)
        End If
        Set rFind = .FindNext(rFind)
    Loop While Not rFind Is Nothing And rFind.Address <> sFirstAddress

    rDelete.EntireRow.Delete

End If
End With
Application.ScreenUpdating = False
End Sub

【问题讨论】:

  • 可以更改为执行以下操作:根据列名和单元格值删除一行?或多个列名和单元格?例如:我想在名为“状态”的列中删除任何值为“完成”的内容,但我可能还想在名为“第二状态”的列中删除任何“完成”的内容..ty

标签: vba excel


【解决方案1】:
Private Sub TestDeleteRows()
Dim rFind As Range
Dim rDelete As Range
Dim strSearch As String
Dim sFirstAddress As String
Dim sh As Worksheet

strSearch = "Completed"
Set rDelete = Nothing

Application.ScreenUpdating = False
For Each sh In ThisWorkbook.Sheets
With sh.Columns("A:AO")
Set rFind = .Find(strSearch, LookIn:=xlValues, LookAt:=xlPart, SearchDirection:=xlNext, MatchCase:=False)
If Not rFind Is Nothing Then
    sFirstAddress = rFind.Address
    Do
        If rDelete Is Nothing Then
            Set rDelete = rFind
        Else
            Set rDelete = Application.Union(rDelete, rFind)
        End If
        Set rFind = .FindNext(rFind)
    Loop While Not rFind Is Nothing And rFind.Address <> sFirstAddress

    rDelete.EntireRow.Delete
    Set rDelete = Nothing
End If
End With
Next sh
Application.ScreenUpdating = False
End Sub

【讨论】:

  • 您好,出现错误“编译错误:” For Each 只能遍历集合对象或数组“发生了什么?
  • 抱歉,可以试试修改后的代码吗?我正在使用 count 方法,但删除了它,以便它只能访问工作表集合本身。对此感到抱歉。
  • 对不起,现在它显示“运行时错误 1004:方法“对象_应用程序的联合失败”对于 else 下的行。但似乎仍然可以在工作表 1 上工作
  • 好的,也许我们需要将 rDelete 重置为空,因为如果您使用多张工作表并且它至少运行一次,则 if 语句不会评估为 True。试试修改后的版本,让我知道它是否适合你。
  • 你好,我认为你是对的!它现在可以正常工作了!太棒了^^
猜你喜欢
  • 1970-01-01
  • 2013-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-10
  • 2017-03-07
相关资源
最近更新 更多