0

我的工作簿中有几张名为“user”、“52”和“Oct-13”等名称的工作表。我需要能够将当前日期与以日期命名的工作表进行比较,例如“Oct-13”。如果当前日期在工作表命名日期之后的任何时间,例如 Oct-13,那么我需要让 VBA 删除工作表。我知道这样做的唯一方法是从工作表名称和当前日期中提取月份和年份并进行比较。有没有更简单的方法?我一直无法找到更简单、更有效的方法。

提前致谢。

4

2 回答 2

0
Sub convertDates()
Dim strDate As String   'Formatted name of current sheet in loop
Dim deleteDate As Date  'The first day sheet is eligible for deletion
Dim currentDate As Date 'The current date as of the last time the Sub was ran
Dim sheet As Worksheet  'Used to loop through the sheets of the workbook

currentDate = DateSerial(Year(Now), Month(Now), Day(Now))

On Error GoTo InvalidDate

For Each sheet In ThisWorkbook.Worksheets
    If InStr(1, sheet.Name, "-", vbBinaryCompare) >= 4 Then
        strDate = Format(DateAdd("m", 1, sheet.Name), "yyyy,mmm")
        deleteDate = DateSerial(Year(strDate), Month(strDate), Day(strDate))
        If deleteDate <= currentDate Then
            Application.DisplayAlerts = False
            sheet.Delete
            Application.DisplayAlerts = True
        End If
    End If
NextSheet:

Next

Exit Sub
InvalidDate:
Err.Clear
'this worksheet's name cannot be interpreted as a date, so ignore and
' resume next
Resume NextSheet

End Sub
于 2013-04-13T19:02:18.490 回答
0

这应该让你开始。我试图通过检查工作表名称是否包含“-”来考虑数字工作表名称(可以不应将其解释为日期。您可能需要对此进行一些改进。

Sub convertDates()
Dim strDate As String
Dim myDate As Date
Dim testDate As Date

testDate = DateSerial(Year(Now), Month(Now), Day(Now))

On Error GoTo InvalidDate
myDate = DateSerial(Year(strDate), Month(strDate), Day(strDate))

'You could do:
 For w = Sheets.Count To w Step -1
    strDate = Sheets(w).Name
    If InStr(1, strDate, "-", vbBinaryCompare) >= 4 Then
        If myDate < testDate Then
            Application.DisplayAlerts = False
            Sheets(w).Delete
            Application.DisplayAlerts = True
        End If
    End If
NextSheet:

 Next

Exit Sub
InvalidDate:
Err.Clear
'this worksheet's name cannot be interpreted as a date, so ignore and
' resume next
Resume NextSheet

End Sub
于 2013-04-12T20:13:34.873 回答