我已经在工作表5上创建了几个宏按钮,如果我在工作表1上就可以使用,但是当我尝试在工作表5上单击该宏的按钮时,它不起作用。如果我在同一工作簿中的另一个工作表上,我需要添加什么以使其选择工作表1?
Sub Delete_External ()
'
' Delete_External Macro
Dim LastRow As Long
Dim i As Long
LastRow = Range("K1000").End(xlUp).Row
For i = LastRow To 1 Step -1
If Range("K" & i) = "External" Then
Range("K" & i).EntireRow.Delete
End If
Next
End Sub
答案 0 :(得分:0)
使用工作表来限定对象。
Sub Delete_External ()
'
' Delete_External Macro
Dim ws as Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim LastRow As Long
Dim i As Long
LastRow = ws.Range("K1000").End(xlUp).Row
For i = LastRow To 1 Step -1
If ws.Range("K" & i) = "External" Then
ws.Range("K" & i).EntireRow.Delete
End If
Next
End Sub
我会避免在循环中删除行,因为这可能会很耗时,具体取决于数据集和条件匹配的数量。考虑这种可遍历您的范围并创建符合条件的单元格的集合(Union
)的替代方法。循环完成后,立即删除Union
。
此方法也已更新为更常见的最后一行查找器方法,并删除了向后循环,因为此方法不需要它!
Sub Delete_External()
'
' Delete_External Macro
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim LR As Long, i As Long
Dim DeleteMe As Range
LR = ws.Range("K" & ws.Rows.Count).End(xlUp).Row
For i = 2 To LR
If ws.Range("K" & i) = "External" Then
If Not DeleteMe Is Nothing Then
Set DeleteMe = Union(DeleteMe, ws.Range("K" & i))
Else
Set DeleteMe = ws.Range("K" & i)
End If
End If
Next i
If Not DeleteMe Is Nothing Then
DeleteMe.EntireRow.Delete
End If
End Sub