试图search一个月/年的列表(excel vba)
我正在使用下面的代码来尝试查找一个月+“销售额”+年的所有实例,然后删除该行。 但是,我得到一个不匹配的错误。 我不认为我的.Find函数可以接受一个列表的参数。 我尝试使用一个循环WITHIN我的循环遍历列表中的所有variables,但仍然得到一个不匹配的错误。 任何想法如何我可以解决这个问题? 谢谢:
'Add months and years for other possibilities Dim mymonth() As String Dim myyear() As String mymonth = Split("September, October, November, December, January, February, March, April, May, June, July, August", ",") myyear = Split("2014, 2015, 2016, 2017, 2018, 2019, 2020", ",") 'now check Set SrchRng = ActiveSheet.Range("C1", ActiveSheet.Range("C65536").End(xlUp)) Do Set c = SrchRng.Find(mymonth + " Sales " + myyear, LookIn:=xlValues) If Not c Is Nothing Then c.EntireRow.Delete Loop While Not c Is Nothing
奖金,如果你能找出一个更好的方式来find任何一年的yyyy格式,而不是手动列出。 我敢肯定,我可以使用datefunction来实现这一点,但我有足够的时间让这只是一个简单的列表…
像这样的东西应该为你工作:
Sub tgr() Dim ws As Worksheet Dim rSearch As Range Dim rFound As Range Dim rDel As Range Dim aYears() As Variant Dim aMonths() As Variant Dim vYear As Variant Dim vMonth As Variant Dim sTemp As String Dim sFirst As String Set ws = ActiveWorkbook.ActiveSheet Set rSearch = ws.Columns("C").EntireColumn aMonths = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") aYears = Array(2014, 2015, 2016, 2017, 2018, 2019, 2020) For Each vYear In aYears For Each vMonth In aMonths sTemp = vMonth & " Sales " & vYear Set rFound = Nothing Set rFound = rSearch.Find(sTemp, rSearch.Cells(rSearch.Cells.Count), xlValues, xlPart, , xlNext, False) If Not rFound Is Nothing Then sFirst = rFound.Address If rDel Is Nothing Then Set rDel = rFound Else Set rDel = Union(rDel, rFound) Do Set rDel = Union(rDel, rFound) Set rFound = rSearch.FindNext(rFound) Loop While rFound.Address <> sFirst End If Next vMonth Next vYear If Not rDel Is Nothing Then rDel.EntireRow.Delete End Sub
批量自动筛选操作通常比单个查找操作循环快得多。
Dim iMonth As Long, iYear As Long, sSales As String With Worksheets("Sheet1") If .AutoFilterMode Then .AutoFilterMode = False With Intersect(.Columns("C"), .UsedRange) For iYear = 2014 To 2020 For iMonth = 1 To 12 sSales = Format(DateSerial(iYear, iMonth, 1), "mmmm \S\a\l\e\s yyyy") .AutoFilter field:=1, Criteria1:=sSales With .Resize(.Rows.Count - 1, 1).Offset(1, 0) If CBool(Application.Subtotal(103, .Cells)) Then .EntireRow.Delete End If End With Next iMonth Next iYear End With If .AutoFilterMode Then .AutoFilterMode = False End With