使用VBA从Excel中删除特定的月份

我正在创buildmacros,这将通过F列循环,并将从2013年4月删除。看来,该macros正在删除所有:-D。 我不知道如何设置它只删除我的标准我试过(Month(Now) - 2) 。 格式的地雷date看起来像DD/MM/YYYY

感谢您的帮助。

 Sub Test1() Dim rgFoundCell As Range Dim toBeDeted As Range Dim firstAddress With Sheets("Sheet1").Range("F:F") Set rgFoundCell = .Find(What:=(Month(Now) - 2)) If Not rgFoundCell Is Nothing Then firstAddress = rgFoundCell.Address Do If toBeDeted Is Nothing Then Set toBeDeted = rgFoundCell.EntireRow Else Set toBeDeted = Union(toBeDeted, rgFoundCell.EntireRow) End If Set rgFoundCell = .FindNext(rgFoundCell) If rgFoundCell Is Nothing Then Exit Do Loop While rgFoundCell.Address <> firstAddress End If End With Application.ScreenUpdating = True If Not toBeDeted Is Nothing Then _ toBeDeted.Delete ' Delete End Sub 

你不能用你认为的方式使用.Find – 只能进行文本匹配或数字匹配比较。 这将使您不得不循环遍历范围中的每个单元格,并在每个单元格上明确运行比较

 Sub Test1() Dim toBeDeleted As Range With Sheets("Sheet1").Range("F:F") For Each c In .Cells If Month(c.Value) = 3 And Year(c.Value) = 2013 Then If toBeDeleted Is Nothing Then Set toBeDeleted = c.EntireRow Else Set toBeDeleted = Union(toBeDeleted, c.EntireRow) End If End If Next End With If Not toBeDeleted Is Nothing Then _ toBeDeleted.Delete ' Delete End Sub 

您可能需要考虑在比完整的F列更精确的范围上运行函数,或者使用数据标记的末尾来检查空白行来停止循环。

尝试这个:

 Sub Test1() On Error GoTo e Application.ScreenUpdating = False Dim rng As Range Dim firstAddress Set rng = Sheets("Sheet1").Range("F1", Sheets("Sheet1").Range("F1").End(xlDown)) Dim i As Long i = 1 While i <= rng.Count If Month(CDate(rng(i))) = 4 And Year(CDate(rng(i))) = 2014 Then rng (i).EntireRow.Delete Else i = i + 1 End If Wend x: Application.ScreenUpdating = True Exit Sub e: MsgBox (Err.Description) Resume x End Sub 

也许尝试减lessF:F范围!