Vba 使用宏从表中删除excel工作表中的整行
我想构建一个宏,根据从第2行到表尾的所有行上运行的if语句从excel工作表中的表中删除行-如果第i行和第B列中的值等于0,我想删除整行 这是我写的代码,但运行时什么也没发生Vba 使用宏从表中删除excel工作表中的整行,vba,excel,Vba,Excel,我想构建一个宏,根据从第2行到表尾的所有行上运行的if语句从excel工作表中的表中删除行-如果第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
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
代码的更正版本如下所示
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).Row '.Select
For i = lastRow To 2 Step -1
If wsCurrent.Cells(i, 2) = 0 Then
wsCurrent.Cells(i, 2).EntireRow.Delete
End If
Next i
End Sub
查找或查找更好的版本如何根据条件删除行从工作表中删除多行的更快方法是使用
Union
功能将需要删除的所有行存储在范围内
退出For
循环后,只需一次命令删除整行DelRng
下面我的代码注释中有更多注释
代码
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
Option Explicit'删除DelRng中1行的所有行
如果不是DelRng,则DelRng.Delete
端接头
一个“快速和愤怒”的代码:
它还将删除B列内容为空的行,而不仔细查看要删除的代码。如果您像这样删除行,则必须在循环中后退。再看一眼就知道第一个问题是行lastRow=Range(“b2”).End(xlDown)。选择不要在这里使用Select
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