简体   繁体   English

Excel-VBA基于当前月份删除行的动态范围

[英]Excel-VBA Delete Dynamic Range of Rows Based on Current Month

I'm trying to create a macro that dynamically deletes a range of rows based on the current month. 我正在尝试创建一个宏,该宏根据当前月份动态删除一系列行。

The first row to be deleted contains the name of the current month. 要删除的第一行包含当前月份的名称。 FindRow attempts to find that row, and then FindRowNumber attempts to store the that row number. FindRow尝试查找该行,然后FindRowNumber尝试存储该行号。

The last row to be deleted is row always 323. When I try to run this macro I always get Runtime error 91. I'm not sure what i'm doing wrong as i'm new to VBA. 最后要删除的行始终是323行。当我尝试运行此宏时,始终会收到运行时错误91。由于我是VBA新手,所以我不确定自己在做什么错。

The relevant worksheet for this code is always the first worksheet in the workbook. 此代码的相关工作表始终是工作簿中的第一个工作表。

Sub Delete_Rows()
    Dim Curr_Month As String
    Dim FindRow As Range
    Dim FindRowNumber As Long

    Curr_Month = MonthName(Month(Now()), False)

With ActiveWorkbook.Worksheets(1)
     Set FindRow = .Range("A:A").Find(What:=Curr_Month, LookIn:=xlValues)
End With

Set FindRowNumber = FindRow.Row

Rows(FindRowNumber & ":323").EntireRow.Delete

End Sub

BigBen has nailed it, but also worth checking first that you have found the search term, to avoid another error, and that the rows being deleted are on the correct sheet (note the extra dot). BigBen已将其钉上钉子,但还应首先检查是否已找到搜索词,以避免再次出现错误,并且已删除的行都在正确的工作表上(请注意额外的点)。

Sub Delete_Rows()

Dim Curr_Month As String
Dim FindRow As Range
Dim FindRowNumber As Long

Curr_Month = MonthName(Month(Now()), False)

With ActiveWorkbook.Worksheets(1)
    Set FindRow = .Range("A:A").Find(What:=Curr_Month, LookIn:=xlValues)
    If Not FindRow Is Nothing Then
        FindRowNumber = FindRow.Row
        .Rows(FindRowNumber & ":323").Delete
    End If
End With

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM