下面的代码应该根据单元格的条件删除整行C 和 D 号给定行中的行是空的)。宏使用过滤器仅显示符合上述条件的行,然后删除相同的可见行。(h/t Jon Acampora @ excelcampus.com)
该宏在单个活动工作簿上运行,其中有一个名为“Sheet0”的工作表。然而,在 VBA 编辑器中,该工作表在对象下被称为“Sheet1”。
代码在此行崩溃并出现错误msg Runtime error 91 object variable or With block variable not set
。见下文。
'1. Apply Filter
ws.UsedRange("$A$1:$D$1000").AutoFilter Field:=3, Criteria1:=""
ws.UsedRange("$A$1:$D$1000").AutoFilter Field:=4, Criteria1:=""
感谢你的协助!
注意:下面的代码包含几行“注释掉”的代码,以显示我尝试修复错误。但我仍然收到运行时错误 1004 - “这无法应用于选定范围。选择单个单元格并重试。”
修改后的代码:
Sub Filter_Del_Visible_Cells()
'Apply a filter to a Range and delete visible rows
'Source: https://www.excelcampus.com/vba/delete-rows-cell-values/
Dim ws As Worksheet
Set ws = ActiveSheet
'Dim wsActiveSheet As Worksheet
'Set wsActiveSheet = Application.ActiveSheet
'wsActiveSheet.UsedRange.Clear
'**************Inserting these lines didn't work
'Dim rUsedRange As Range
'Set rUsedRange = Sheets("Sheet1").UsedRange
'************************
'Set reference to the sheet in the workbook.
'Set ws = ThisWorkbook.Worksheets("Sheet0")
'****************************
'ws.Activate 'not required but allows user to view sheet if warning message appears
'Clear any existing filters
On Error Resume Next
ws.ShowAllData
On Error GoTo 0
'1. Apply Filter
ActiveSheet.Range("A1:D11000").AutoFilter Field:=3, Criteria1:=""
ActiveSheet.Range("A1:D11000").AutoFilter Field:=4, Criteria1:=""
'ws.UsedRange.AutoFilter Field:=3, Criteria1:=""
'ws.UsedRange.AutoFilter Field:=4, Criteria1:=""
'ws.UsedRange("$A$1:$D$1000").AutoFilter Field:=3, Criteria1:=""
'ws.UsedRange("$A$1:$D$1000").AutoFilter Field:=4, Criteria1:=""
'2. Delete Rows
Application.DisplayAlerts = False
ws.Range("B4:G1000").SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
'3. Clear Filter
On Error Resume Next
ws.ShowAllData
On Error GoTo 0
End Sub