设置列值为用户输入,限制为日期格式。

问题描述 投票:0回答:1

我需要一个弹出框,要求用户输入一个日期。我想确保只有DDMMYYYY格式的日期可以上传。

下面的代码可以工作,但是它允许插入任何输入类型。

Call RunSQL("UPDATE Summary " & _
    "SET " & _
    "Date_of_Report = [Enter the Report date in the following format DD/MM/YYYY, with the DD being the last day of the month] " & _
    " WHERE Date_of_Report IS NULL ")

我还想在提示中包含正在更新的文件名,我试着做了以下操作(其中FileNameSelected是一个变量,每次都会包含一个不同的值),但得到一个错误。

Call RunSQL("UPDATE Summary " & _
    "SET " & _
    "Date_of_Report = [Enter the Report date for the '" & FileNameSelected & "' file in the following format DD/MM/YYYY, with the DD beng the last day of the month] " & _
    " WHERE Date_of_Report IS NULL ")

如果有谁能告诉我如何在格式周围设置参数并在提示中包含FileNameSelected变量的值,我会非常感激。

另外对于VBA的弹出框,我知道你使用& vbCrLf & _来为他的消息框创建新的行,我如何用提示符来做这件事?

vba ms-access
1个回答
1
投票

这就是我如何验证你的日期。用MMDDYYYY格式会容易很多。使用DDMM,你必须完全处理它,否则你有一个风险,Access混合月和日。

Public Sub Test_date_prompt()


    Dim strInpput As String
    Dim dtConverted As Date
    Dim OK As Boolean
    Dim FileNameSelected As String

    On Error GoTo Err_handler

    OK = False


    FileNameSelected = "Anything for this example"

    strinput = InputBox("Enter the Report date for the '" & FileNameSelected & "' file in the following format DD/MM/YYYY, with the DD being the last day of the month", "Enter date")

    ' testing if user inputed 10 characters
    If Len(strinput) = 10 Then
        ' testing if / separators are at the right place
        If Mid(strinput, 3, 1) = "/" And Mid(strinput, 6, 1) = "/" Then
            ' testing if DD, MM, YYYY placeholders are all numeric
            If IsNumeric(Left(strinput, 2)) And IsNumeric(Mid(strinput, 4, 2)) And IsNumeric(Right(strinput, 4)) Then
                'looks good
                OK = True
            End If
        End If
    End If

    If Not OK Then
        ' not good, abording process
        MsgBox "You have not entered a valid date in DD/MM/YYYY format !", vbExclamation, "Abording"
        GoTo Exit_Sub
    End If

    ' Converting in date which ensure a valid date, otherwise an error will occur
    dtConverted = DateSerial(Right(strinput, 4), Mid(strinput, 4, 2), Left(strinput, 2))


    ' if your Date_of_report type is DATE, do :
'    Call RunSQL("UPDATE Summary " & _
        "SET " & _
        "Date_of_Report = #" & Format(dtConverted, "MM/DD/YYYY") & "# " & _
        " WHERE Date_of_Report IS NULL ")

    ' if your Date_of_report type is STRING (bad!), do :
 '   Call RunSQL("UPDATE Summary " & _
        "SET " & _
        "Date_of_Report = '" & Format(dtConverted, "DD/MM/YYYY") & "' " & _
        " WHERE Date_of_Report IS NULL ")



Exit_Sub:
    Exit Sub

Err_handler:
    MsgBox Err.Description
    Resume Exit_Sub

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.