我的工作表中有空行,我想以这样的方式删除它们:如果上面的行或下面的行不为空,我不想删除它们。我不想删除它们,因此在之前填充的行下方至少有 1 个空行。
我知道如何删除工作表中的空行:
Worksheets("Sheet1").Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
但我不知道如何改变它来实现它。需要一些关于如何执行此操作的指导。
我的代码现在看起来像这样:
For Each ws In Workbooks(newwb).Sheets
If (ws.Name <> "Sheet1") And (ws.Name <> "Sheet2") And (ws.Name <> "Sheet3") Then
'ws.Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
lRow = ws.Range("A" & Rows.Count).End(xlUp).Row
For i = 1 To lRow
If Application.WorksheetFunction.CountA(ws.Range("A" & i & ":O" & i + 2)) = 0 Then
If IsEmpty(rngBlanks) Then
Set rngBlanks = ws.Rows(i + 1)
Else
Set rngBlanks = Union(rngBlanks, ws.Rows(i + 1))
End If
End If
Next i
rngBlanks.EntireRow.Delete
Set rngBlanks = Nothing
Else
ws.Delete
End If
Next
执行时,它给我一个运行时错误“5”:行中的过程调用或参数无效Set rngBlanks = Union(rngBlanks, ws.Rows(i+1))
最佳答案
I know how to delete empty rows in a sheet:
没有。这是删除空行的错误方法,并且当您有多列时不起作用。您可能想查看 This 。此函数使用循环和 Application.WorksheetFunction.CountA
。或者,您也可以使用.Autofilter
。
But I am not sure how to change this to implement that. Need some guidance on how to do this.
使用与上面链接中我的回答中所示相同的逻辑。
'~~> Loop through the rows to find which range is blank
For i = 1 To lRow
'~~> Checking 3 rows in one go
If Application.WorksheetFunction.CountA(Range("A" & i & ":J" & i + 2)) = 0 Then
If rngBlanks Is Nothing Then
Set rngBlanks = .Rows(i + 1)
Else
Set rngBlanks = Union(rngBlanks, .Rows(i + 1))
End If
End If
Next i
编辑
请尝试这个(未经测试)
For Each ws In Workbooks(newwb).Sheets
Select Case ws.Name
Case "Sheet1", "Sheet2", "Sheet3"
Case Else
With ws
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 1 To lRow
If i = .Rows.Count - 1 Then Exit For
If Application.WorksheetFunction.CountA(.Range("A" & i & ":O" & i + 2)) = 0 Then
If rngBlanks Is Nothing Then
Set rngBlanks = .Rows(i + 1)
Else
Set rngBlanks = Union(rngBlanks, .Rows(i + 1))
End If
End If
Next i
If Not rngBlanks Is Nothing Then
rngBlanks.Delete
Set rngBlanks = Nothing
End If
End With
End Select
Next ws
关于vba - 如何在VBA中删除前一行或后一行非空的空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36587310/