从 InputBox 获取日期

Getting date from an InputBox

提问人:Light 提问时间:10/13/2023 最后编辑:Light 更新时间:10/14/2023 访问量:82

问:

我正在通过一个按钮处理 Excel VBA。单击该按钮后,将弹出一个输入框,询问用户下个月是什么。输入新月份的日期将创建一个以月份和年份命名的新工作簿。如果用户正确输入日期,它可以正常工作。但是,如果用户在输入框中未输入任何内容,则通过取消输入或输入其他数据而不是日期。将弹出错误代码 13:类型不匹配。似乎 DATE 变量不能为空。

这是我的代码:

Sub NewMonth_button()

Dim Date_Today As Date
Dim nwFilename As String

Date_Today = InputBox("Please enter YEAR-Month")

nwFilename = "Daily Journal_" & Year(Date_Today) & "_" & Month(Date_Today)

Worksheets(Array("list", "data", "Fill", "Archive>")).Copy
ActiveWorkbook.SaveAs filename:=ThisWorkbook.Path & Application.PathSeparator & nwFilename

End Sub

我尝试过这样的方法:

If Date_Today = "" then
exit sub
end if

就在这条线之后,但它不起作用。Date_Today = InputBox("Please enter YEAR-Month")

有什么方法可以避免这些吗? 非常感谢。

Excel VBA 日期

评论

2赞 braX 10/13/2023
learn.microsoft.com/en-us/office/vba/language/reference/......
0赞 Siddharth Rout 10/13/2023
stackoverflow.com/questions/34049088/......
2赞 Siddharth Rout 10/13/2023
此外,您可能希望看到这个,而不是使用输入框或文本框来接受日期

答:

1赞 Gustav 10/13/2023 #1

喜欢这个:

Sub NewMonth_button()

    Dim Date_Today As Date
    Dim Date_Text  As String
    Dim nwFilename As String

    Date_Text = InputBox("Please enter YEAR-Month")
    If IsDate(Date_Text & "-01") Then
        Date_Today = DateValue(Date_Text & "-01")
        nwFilename = "Daily Journal_" & Format(Date_Today, "yyyy_mm")

        Worksheets(Array("list", "data", "Fill", "Archive>")).Copy
        ActiveWorkbook.SaveAs filename:=ThisWorkbook.Path & Application.PathSeparator & nwFilename
    End If

End Sub

评论

1赞 Light 10/13/2023
谢谢你的回答。效果很好。简单,正是我需要的。我不仅学会了功能,还学会了功能。无需再使用。IsDateFormatYear(Date_Today) & "_" & Month(Date_Today)
1赞 CDP1802 10/14/2023
当然不是Format(Date_Today, "yyyy_mm")Format(Date_Today & "yyyy_mm")
1赞 VBasic2008 10/13/2023 #2

创建每月工作簿

Sub CreateMonthlyWorkbook()
     
    ' Define constants.
    Const PROC_TITLE As String = "Create Monthly Workbook"
    Const DST_FILE_NAME_LEFT As String = "Daily Journal_"
    ' The following two need to be in sync:
    Const DST_FILE_EXTENSION As String = ".xlsx"
    Dim dFileFormat As XlFileFormat: dFileFormat = xlOpenXMLWorkbook
    Dim dSheetNames() As Variant:
    dSheetNames = Array("list", "data", "Fill", "Archive>")
    Const PERIOD_DELIMITER As String = "-" ' single character!
    Const PERIOD_FILE_DELIMITER As String = "_"
    Const PERIOD_YEAR_FORMAT As String = "yyyy" ' fixed!
    Const PERIOD_MONTH_FORMAT As String = "m" ' or 'mm' fixed!
    Const YEAR_MIN As Long = 2001 ' Excel Min = 1900
    Const YEAR_MAX As Long = 2030 ' Excel Max = 9999
    Const MONTH_MIN As Long = 1
    Const MONTH_MAX As Long = 12
    
    ' Reference the source workbook.
    Dim swb As Workbook: Set swb = ThisWorkbook ' workbook containing this code
    
    ' Determine the destination folder path.
    Dim dFolderPath As String: dFolderPath = swb.Path
    
    ' Determine the input parameters.
    Dim PeriodFormat As String: PeriodFormat = PERIOD_YEAR_FORMAT _
        & PERIOD_DELIMITER & PERIOD_MONTH_FORMAT
    Dim iPrompt As String: iPrompt = "Please enter the period in """ _
        & PeriodFormat & """ format:"
    Dim iDefault As String: iDefault = Format(Date, PeriodFormat) ' current
       
    ' Input.
       
    Application.ScreenUpdating = False
       
    Dim PeriodInput As Variant, PerLen As Long, DelPos As Long
    Dim YearValue As Variant, MonthValue As Variant, IsPeriodValid As Boolean
    
    Do
        ' Input.
        PeriodInput = Application _
            .InputBox(iPrompt, PROC_TITLE, iDefault, , , , , 2) ' 2 - string
        ' Canceled.
        If VarType(PeriodInput) = vbBoolean Then
            MsgBox "Canceled. Workbook not created.", _
                vbExclamation, PROC_TITLE
            Exit Sub
        End If
        ' Not canceled.
        PerLen = Len(PeriodInput)
        If PerLen = 6 Or PerLen = 7 Then
            DelPos = InStr(PeriodInput, PERIOD_DELIMITER)
            If DelPos = 5 Then
                YearValue = Left(PeriodInput, 4)
                If YearValue Like "####" Then
                    YearValue = CLng(YearValue)
                    If YearValue >= YEAR_MIN And YearValue <= YEAR_MAX Then
                        MonthValue = Right(PeriodInput, PerLen - DelPos)
                        If MonthValue Like "#" Or MonthValue Like "##" Then
                            MonthValue = CLng(MonthValue)
                            If MonthValue >= MONTH_MIN _
                                    And MonthValue <= MONTH_MAX Then
                                IsPeriodValid = True
                            End If
                        End If
                    End If
                End If
            End If
        End If
    Loop Until IsPeriodValid = True
    
    ' Build the destination file path.
    
    Dim DateString As String: DateString = YearValue & PERIOD_FILE_DELIMITER _
        & Format(MonthValue, String(Len(PERIOD_MONTH_FORMAT) - 1, "0") & "#")
    Dim dFileName As String:
    dFileName = DST_FILE_NAME_LEFT & DateString & DST_FILE_EXTENSION
    Dim dFilePath As String:
    dFilePath = dFolderPath & Application.PathSeparator & dFileName
    
    If Len(Dir(dFilePath)) > 0 Then
        MsgBox "The file """ & dFileName & """ already exists in folder """ _
            & dFolderPath & """!", vbCritical, PROC_TITLE
        Exit Sub
    End If
    
    ' Copy the sheets to a new workbook.
    swb.Sheets(dSheetNames).Copy
    
    ' Save (and close) the newly created workbook.
    With Workbooks(Workbooks.Count)
        .SaveAs Filename:=dFilePath, FileFormat:=dFileFormat
        '.Close SaveChanges:=False
    End With

    Application.ScreenUpdating = True

    ' Inform.
    MsgBox "Created workbook """ & dFileName & """ in folder """ _
            & dFolderPath & """.", vbInformation, PROC_TITLE

End Sub

评论

0赞 Light 10/13/2023
感谢您的详细代码。虽然这对我来说很复杂,但它给了我很多想法。