在此处输入代码将自动创建工作表。该工作表将有一个从当前日期开始2天输入的日期。我很难在它变成3天后删除该工作表。请查看下面的代码,了解当前的状态。
For Each ws In Worksheets
If ws.Name = Format(Date - 2, "MM-DD-YYYY") Then
Application.DisplayAlerts = False
Sheets(Date - 2, "MM-DD-YYYY").Delete
Application.DisplayAlerts = True
答案 0 :(得分:0)
您不会在Sheets集合中返回格式化的字符串。
For Each ws In Worksheets
If ws.Name = Format(Date - 2, "MM-DD-YYYY") Then
Application.DisplayAlerts = False
Sheets(Format(Date - 2, "MM-DD-YYYY")).Delete '<~~ identified here
'alternate
'ws.delete
Application.DisplayAlerts = True
exit for '<~~ no point in continuing since only one worksheet could have that name
实际上没有必要两次构建工作表名称。如果它通过了名测试,则ws
是您要删除的工作表。
我开始考虑可能会干扰“ 3天大”规则的周末和节假日。这将删除任何名称早于或早于三个工作日的字符串日期的工作表。
For Each ws In Worksheets
If cdate(ws.Name) <= APPLICATION.WORKDAY(Date, -3) Then
Application.DisplayAlerts = False
ws.delete
Application.DisplayAlerts = True
end if
NEXT WS
答案 1 :(得分:0)
如果我理解您的问题,可以尝试以下代码:
Sub test()
For Each ws In Worksheets
If ws.Name = Format(Date - 2, "MM-DD-YYYY") Then
Application.DisplayAlerts = False
'control the date and delete the sheet
If (ws.Name = Format(Date - 2, "MM-DD-YYYY")) Then
ws.Delete
Application.DisplayAlerts = True
End If
End If
Next ws
End Sub
例如如果今天是01-02-2019,则宏会删除日期为12-31-2018(MM-DD-YYYY)的工作表。如果要删除3天前的工作表,则必须在3(宏内)中更改值2。
希望这会有所帮助!
答案 2 :(得分:0)
cBlnWithoutConfirmation
至True
。'*******************************************************************************
' Purpose: Deletes all sheets named by a date in format MM-DD-YYYY
' that are at least old as specified.
'*******************************************************************************
Sub DeleteOldSheets()
Const cIntAge As Integer = 3 ' Age of Sheet (Days)
Const cBlnWithoutConfirmation = False ' Enable Delete Without Confirmation
Dim vntDate As Variant ' Date Array
Dim vntSheetDate As Date ' Sheet Date
Dim i As Integer ' Sheets Counter
With ThisWorkbook
For i = 1 To .Sheets.Count
With .Sheets(i)
vntDate = Split(.Name, "-")
On Error Resume Next
vntSheetDate = DateSerial(vntDate(2), vntDate(0), vntDate(1))
If Err Then
On Error GoTo 0
Else
If Date - vntSheetDate + 1 > cIntAge Then
If cBlnWithoutConfirmation Then
Application.DisplayAlerts = False
.Delete
Application.DisplayAlerts = True
Else
.Delete
End If
End If
End If
End With
Next
End With
End Sub
'*******************************************************************************