如何根据条件删除 Excel 工作表中的行

发布于 2024-12-11 07:43:07 字数 119 浏览 0 评论 0原文

我有一个 Excel 工作簿,位于 A 列的 worksheet1 中,如果该列的值 = ERR 我希望将其删除(整行),这怎么可能?

PS:请记住,我以前从未使用过 VBA 或宏,因此非常感谢详细的描述。

I have an excel workbook, in worksheet1 in Column A, IF the value of that column = ERR I want it to be deleted (the entire row), how is that possible?

PS: keep in mind that I have never used VBA or Macros before, so detailed description is much appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

暖伴 2024-12-18 07:43:07

手动或使用 VBA 使用自动过滤器(如下所示)是删除行的非常有效的方法

下面的代码

  1. 适用于整个使用范围,即将处理空白
  2. 可以通过更改 strSheets = 轻松适应其他工作表数组(1, 4)。即此代码当前在第一张和第四张纸上运行

     选项显式
    
    
    子 KillErr()
    昏暗的工作表
    变暗lRow只要
    调暗颜色只要长
    调暗 rng1 作为范围
    昏暗的 strSheets()
    Dim strws 作为变体
    strSheets = 数组(1, 4)
    对于 strSheets 中的每个 strws
        设置 ws = Sheets(strws)
        lRow = ws.Cells.Find("*", , xlValues, , xlByRows, xlPrevious).Row
        lngCol = ws.Cells.Find("*", , xlValues, , xlByColumns, xlPrevious).Column
        应用程序.ScreenUpdating = False
        ws.Rows(1).Insert
        设置 rng1 = ws.Range(ws.Cells(1, lngCol), ws.Cells(lRow + 1, lngCol))
        使用 rng1.Offset(0, 1)
            .FormulaR1C1 = "=RC1=""ERR"""
            .自动筛选字段:=1,条件1:=“真”
            .EntireRow.Delete
            出错时继续下一步
            .整列.删除
            出错时转到 0
        结束于
    下一个
    应用程序.ScreenUpdating = True
    结束子
    

Using an autofilter either manually or with VBA (as below) is a very efficient way to remove rows

The code below

  1. Works on the entire usedrange, ie will handle blanks
  2. Can be readily adpated to other sheets by changing strSheets = Array(1, 4). ie this code currently runs on the first and fourth sheets

     Option Explicit
    
    
    Sub KillErr()
    Dim ws As Worksheet
    Dim lRow As Long
    Dim lngCol As Long
    Dim rng1 As Range
    Dim strSheets()
    Dim strws As Variant
    strSheets = Array(1, 4)
    For Each strws In strSheets
        Set ws = Sheets(strws)
        lRow = ws.Cells.Find("*", , xlValues, , xlByRows, xlPrevious).Row
        lngCol = ws.Cells.Find("*", , xlValues, , xlByColumns, xlPrevious).Column
        Application.ScreenUpdating = False
        ws.Rows(1).Insert
        Set rng1 = ws.Range(ws.Cells(1, lngCol), ws.Cells(lRow + 1, lngCol))
        With rng1.Offset(0, 1)
            .FormulaR1C1 = "=RC1=""ERR"""
            .AutoFilter Field:=1, Criteria1:="TRUE"
            .EntireRow.Delete
            On Error Resume Next
            .EntireColumn.Delete
            On Error GoTo 0
        End With
    Next
    Application.ScreenUpdating = True
    End Sub
    
场罚期间 2024-12-18 07:43:07
  sub delete_err_rows()
      Dim Wbk as Excel.workbook  'create excel workbook object
      Dim Wsh as worksheet       ' create excel worksheet object 
      Dim Last_row as long
      Dim i as long
      Set Wbk = Thisworkbook ' im using thisworkbook, assuming current workbook
                             ' if you want any other workbook just give the name 
                             ' in invited comma as "workbook_name"
      Set Wsh ="sheetname"   ' give the sheet name here 
      Wbk.Wsh.activate
     ' it means Thisworkbook.sheets("sheetname").activate
     ' here the sheetname of thisworkbook is activated
     ' or if you want looping between sheets use thisworkbook.sheets(i).activate
     ' put it in loop , to loop through the worksheets
     ' use thisworkbook.worksheets.count to find number of sheets in workbook
     Last_row = ActiveSheet.Cells(Rows.count, 1).End(xlUp).Row 'to find the lastrow of the activated sheet
          For i = lastrow To 1 step -1
             if activesheet.cells(i,"A").value = "yourDesiredvalue"
                  activesheet.cells(i,"A").select  ' select the row
                  selection.entirerow.delete       ' now delete the entire row
             end if
          Next i
   end sub

请注意,您使用 activesheet 执行的任何操作都会影响当前激活的工作表

正如您所说,您是初学者,为什么不记录一个宏并检查一下,这是通过查看后台代码来自动化流程的最佳方法

只需找到工作表上的“宏”选项卡并单击“录制新宏”,然后选择任意一行并执行您想做的操作,例如删除整行,只需删除整行,然后返回“宏”选项卡并单击“停止录制”。

现在单击 alt+F11 ,这将带您进入 VBA 编辑器,您可以在 vba 项目资源管理器字段中找到一些工作表和模块,如果您没有找到它,请使用 VBA 编辑器的视图选项卡进行搜索,现在单击 module1 并查看录制的宏,您会发现类似的内容

        selection.entirerow.delete

我希望我对您有所帮助,如果您需要更多帮助,请告诉我,谢谢

  sub delete_err_rows()
      Dim Wbk as Excel.workbook  'create excel workbook object
      Dim Wsh as worksheet       ' create excel worksheet object 
      Dim Last_row as long
      Dim i as long
      Set Wbk = Thisworkbook ' im using thisworkbook, assuming current workbook
                             ' if you want any other workbook just give the name 
                             ' in invited comma as "workbook_name"
      Set Wsh ="sheetname"   ' give the sheet name here 
      Wbk.Wsh.activate
     ' it means Thisworkbook.sheets("sheetname").activate
     ' here the sheetname of thisworkbook is activated
     ' or if you want looping between sheets use thisworkbook.sheets(i).activate
     ' put it in loop , to loop through the worksheets
     ' use thisworkbook.worksheets.count to find number of sheets in workbook
     Last_row = ActiveSheet.Cells(Rows.count, 1).End(xlUp).Row 'to find the lastrow of the activated sheet
          For i = lastrow To 1 step -1
             if activesheet.cells(i,"A").value = "yourDesiredvalue"
                  activesheet.cells(i,"A").select  ' select the row
                  selection.entirerow.delete       ' now delete the entire row
             end if
          Next i
   end sub

Note any operations that you do using activesheet , will be affected on the currently activated sheet

As your saying your a begginner, why dont you record a macro and check out, Thats the greatest way to automate your process by seeing the background code

Just find the macros tab on the sheet and click record new macro , then select any one of the row and do what you wanted to do , say deleting the entire row, just delete the entire row and now go back to macros tab and click stop recording .

Now click alt+F11 , this would take you to the VBA editor there you find some worksheets and modules in the vba project explorer field , if you dont find it search it using the view tab of the VBA editor, Now click on module1 and see the recorded macro , you will find something like these

        selection.entirerow.delete

I hope i helped you a bit , and if you need any more help please let me know, Thanks

同展鸳鸯锦 2024-12-18 07:43:07

最快的方法:

Sub DeleteUsingAutoFilter()

    Application.ScreenUpdating = False

    With ActiveSheet
        .AutoFilterMode = False

        .Columns("A").AutoFilter Field:=1, Criteria1:="ERR"

        .AutoFilter.Range.Offset(1, 0).EntireRow.Delete        

        .AutoFilterMode = False
    End With

    Application.ScreenUpdating = True

End Sub

第二快的方法(这个方法也有很多变化):

Sub DeleteWithFind()
    Dim rFound As Range, rDelete As Range
    Dim sAddress As String

    Application.ScreenUpdating = False

    With Columns("A")
        Set rFound = .Find(What:="ERR", After:=.Resize(1, 1), SearchOrder:=xlByRows)

        If Not rFound Is Nothing Then
            Set rDelete = rFound                
            Do
                Set rDelete = Union(rDelete, rFound)
                Set rFound = .FindNext(rFound)
            Loop While rFound.Row > rDelete.Row                
        End If

        If Not rDelete Is Nothing Then rDelete.EntireRow.Delete

    End With

    Application.ScreenUpdating = True

End Sub

多张纸的自动过滤方法:

Sub DeleteUsingAutoFilter()
    Dim vSheets As Variant
    Dim wsLoop As Worksheet

    Application.ScreenUpdating = False

    '// Define worksheet names here
    vSheets = Array("Sheet1", "Sheet2")

    For Each wsLoop In Sheets(vSheets)

         With wsLoop
             .AutoFilterMode = False

             .Columns("A").AutoFilter Field:=1, Criteria1:="ERR"

             .AutoFilter.Range.Offset(1, 0).EntireRow.Delete

             .AutoFilterMode = False
         End With

    Next wsLoop

    Application.ScreenUpdating = True

End Sub

Fastest method:

Sub DeleteUsingAutoFilter()

    Application.ScreenUpdating = False

    With ActiveSheet
        .AutoFilterMode = False

        .Columns("A").AutoFilter Field:=1, Criteria1:="ERR"

        .AutoFilter.Range.Offset(1, 0).EntireRow.Delete        

        .AutoFilterMode = False
    End With

    Application.ScreenUpdating = True

End Sub

Second fastest method (lots of variations to this one too):

Sub DeleteWithFind()
    Dim rFound As Range, rDelete As Range
    Dim sAddress As String

    Application.ScreenUpdating = False

    With Columns("A")
        Set rFound = .Find(What:="ERR", After:=.Resize(1, 1), SearchOrder:=xlByRows)

        If Not rFound Is Nothing Then
            Set rDelete = rFound                
            Do
                Set rDelete = Union(rDelete, rFound)
                Set rFound = .FindNext(rFound)
            Loop While rFound.Row > rDelete.Row                
        End If

        If Not rDelete Is Nothing Then rDelete.EntireRow.Delete

    End With

    Application.ScreenUpdating = True

End Sub

Autofilter method for multiple sheets:

Sub DeleteUsingAutoFilter()
    Dim vSheets As Variant
    Dim wsLoop As Worksheet

    Application.ScreenUpdating = False

    '// Define worksheet names here
    vSheets = Array("Sheet1", "Sheet2")

    For Each wsLoop In Sheets(vSheets)

         With wsLoop
             .AutoFilterMode = False

             .Columns("A").AutoFilter Field:=1, Criteria1:="ERR"

             .AutoFilter.Range.Offset(1, 0).EntireRow.Delete

             .AutoFilterMode = False
         End With

    Next wsLoop

    Application.ScreenUpdating = True

End Sub
橘香 2024-12-18 07:43:07

假设 A 列的单元格中始终有值并且数据位于第一个工作表中,那么类似这样的操作应该可以满足您的要求:

Sub deleteErrRows()
    Dim rowIdx As Integer
    rowIdx = 1

    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets(1)

    While ws.Cells(rowIdx, 1).Value <> ""
        If ws.Cells(rowIdx, 1).Value = "ERR" Then
            ws.Cells(rowIdx, 1).EntireRow.Delete
        Else
            rowIdx = rowIdx + 1
        End If
    Wend
End Sub

Assuming there are always values in the cells in column A and that the data is in the first sheet, then something like this should do what you want:

Sub deleteErrRows()
    Dim rowIdx As Integer
    rowIdx = 1

    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets(1)

    While ws.Cells(rowIdx, 1).Value <> ""
        If ws.Cells(rowIdx, 1).Value = "ERR" Then
            ws.Cells(rowIdx, 1).EntireRow.Delete
        Else
            rowIdx = rowIdx + 1
        End If
    Wend
End Sub
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文