如何使用日期变量选择工作表?

时间:2019-06-29 16:32:11

标签: excel vba date variables

我一直在尝试使用此变量szTodayDate选择和删除工作表,但我一直收到运行时错误9。

Option Explicit
Dim szTodayDate As String

Public Sub AddSheetsTodayDate()

    szTodayDate = Format(Date, "dd-mmm-yy")

    On Error GoTo MakeSheet
    Sheets(szTodayDate).Activate
    Exit Sub
MakeSheet:
    Sheets.Add , Worksheets(Worksheets.Count)
    ActiveSheet.Name = szTodayDate

End Sub

Public Sub RecordProgress()
    Worksheets(szTodayDate).Select  
End Sub

2 个答案:

答案 0 :(得分:0)

问题出在您声明szTodayDate上。更改为:
Public szTodayDate As String

答案 1 :(得分:0)

这将为您工作:

我已经使用Answer中Rory提到的Evaluate来检查工作表是否存在。

Option Explicit
Public szTodayDate As String

Public Sub AddSheetsTodayDate()

    Dim WorksheetExists As Boolean
    Dim ws As Worksheet

        szTodayDate = format(Now, "dd-mmm-yy")
        WorksheetExists = Evaluate("ISREF('" & szTodayDate & "'!A1)")

    If Not WorksheetExists Then

        Sheets.Add , Worksheets(Worksheets.Count)
        ActiveSheet.Name = szTodayDate

    Else: Sheets(szTodayDate).Activate

    End If

End Sub

Public Sub RecordProgress()
    Worksheets(szTodayDate).Select  
End Sub