创buildExcelmacros以同时删除多行
我在网上find了一个代码,并想对它进行编辑。 代码是在VBA中,我想要macros代码删除多行而不是一个。 这里是代码:
Sub findDelete() Dim c As String Dim Rng As Range c = InputBox("FIND WHAT?") Set Rng = Nothing Set Rng = Range("A:A").Find(what:=c, _ After:=Range("A1"), _ LookIn:=xlFormulas, _ lookat:=xlPart, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=False) Rng.EntireRow.Delete shift:=xlUp End Sub
使用Autofilter
并删除VisibleCells
,而不是使用find
Sub findDelete() Dim c As String, Rng As Range, wks as Worksheet c = InputBox("FIND WHAT?") Set wks = Sheets(1) '-> change to suit your needs Set Rng = wks.Range("A:A").Find(c, After:=Range("A1"), LookIn:=xlFormulas, _ lookat:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False) If Not Rng Is Nothing Then With wks .Range(.Range("A1"), .Range("A" & .Rows.Count).End(xlUp)).AutoFilter 1, c Set Rng = Intersect(.UsedRange, .UsedRange.Offset(1), .Range("A:A")).SpecialCells(xlCellTypeVisible) Rng.Offset(1).EntireRow.Delete End With End If End Sub
编辑
用多个值replaceInputBox来查找/删除这样做:
Option Explicit Sub FindAndDeleteValues() Dim strValues() as String strValues() = Split("these,are,my,values",",") Dim i as Integer For i = LBound(strValues()) to UBound(strValues()) Dim c As String, Rng As Range, wks as Worksheet c = strValues(i) '.... then continue with code as above ... Next End Sub
只要把它包装在一个While
循环中。
Sub findDelete() Dim c As String Dim Rng As Range c = InputBox("FIND WHAT?") Set Rng = Nothing Do While Not Range("A:A").Find(what:=c) Is Nothing Set Rng = Range("A:A").Find(what:=c, _ After:=Range("A1"), _ LookIn:=xlFormulas, _ lookat:=xlPart, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=False) Rng.EntireRow.Delete shift:=xlUp Loop End Sub
您已经有了删除Rng.EntireRow.Delete shift:=xlUp
行的代码Rng.EntireRow.Delete shift:=xlUp
,您需要的是将范围设置为您要删除的行的代码。 像往常一样在VBA中,这可以通过很多方式来完成:
'***** By using the Rng object Set Rng = Rows("3:5") Rng.EntireRow.Delete shift:=xlUp Set Rng = Nothing '***** Directly Rows("3:5").EntireRow.Delete shift:=xlUp
你的Find
语句只能findc
的第一个出现,这就是为什么它不会删除更多的那一行。