【问题标题】:Delete entire rows in excel sheet from a table using macro使用宏从表中删除excel工作表中的整行
【发布时间】:2018-04-02 13:33:46
【问题描述】:

我想构建一个宏,该宏根据 if 语句从 Excel 工作表中的表中删除行,该语句在从第 2 行到表末尾的所有行上运行 - 如果第 i 行和 B 列中的值等于 0 我想删除整行。

这是我写的代码,但是当我运行它时没有任何反应

Sub deleteZeroRows()

'loop for deleting zero rows
Dim wbCurrent As Workbook
Dim wsCurrent As Worksheet
Dim nLastCol, i As Integer

Set wbCurrent = ActiveWorkbook
Set wsCurrent = wbCurrent.ActiveSheet

Dim lastRow As Long

lastRow = Range("b2").End(xlDown).Select

For i = 2 To lastRow
    If wsCurrent.Cells(i, 2) = 0 Then
    wsCurrent.Cells(i, 2).EntireRow.Delete
    End If
Next i

End Sub 

【问题讨论】:

  • 如果您像删除行一样不仔细查看代码,则必须在循环中倒退。再看一遍告诉我,第一个问题是lastRow = Range("b2").End(xlDown).Select 此处不要使用Select 这一行

标签: vba excel


【解决方案1】:

从工作表中删除多行的更快方法是使用Union 函数将所有需要删除的Rows 存储在Range 中。

退出 For 循环后,只需在一个命令中删除整行 DelRng

下面我的代码的 cmets 中有更多注释。

代码

Option Explicit  '<-- always use this at the top of your code

Sub deleteZeroRows()

Dim wbCurrent As Workbook
Dim wsCurrent As Worksheet
Dim lastRow As Long, nLastCol As Long, i As Long
Dim DelRng As Range

Set wbCurrent = ActiveWorkbook '<-- try to avoid using Active...
Set wsCurrent = wbCurrent.ActiveSheet '<-- try to avoid using Active...

With wsCurrent
    lastRow = .Cells(.Rows.Count, "B").End(xlUp).Row ' get last row in column B

    For i = 2 To lastRow
        If .Range("B" & i).Value = 0 Then
            If Not DelRng Is Nothing Then
                ' add another row to DelRng range
                Set DelRng = Application.Union(DelRng, .Rows(i))
            Else
                Set DelRng = .Rows(i)
            End If
        End If
    Next i
End With

' if there's at least 1 row to be deleted >> delete all rows in DelRng at 1-line
If Not DelRng Is Nothing Then DelRng.Delete

End Sub

【讨论】:

    【解决方案2】:

    “速度与激情”代码:

    Sub deleteZeroRows()
        With Range("B2", Cells(Rows.Count, 2).End(xlUp)) 'reference column B cells from row 2 down to last not empty one
            .Replace what:=0, lookat:=xlWhole, replacement:="" ' replace 0's with blanks
            If WorksheetFunction.CountBlank(.Cells) > 0 Then .SpecialCells(XlCellType.xlCellTypeBlanks).EntireRow.Delete ' delete rows where referenced range is blank
        End With
    End Sub
    

    这也会删除 B 列内容为空白的行

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2014-07-08
      • 1970-01-01
      • 2014-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多