Application.Match函数不适用于日期(VBA)

时间:2018-10-03 22:26:49

标签: vba excel-vba

我试图将验证规则添加到输入框宏中,该宏将要求用户在输入框中输入四个日历季度结束日期的最后一个日期。我正在使用If ElseIf Else循环来运行验证规则。正确的输入应该是“ 03/31 / yyyy”,“ 06/30 / yyyy”,“ 09/30 / yyyy”或12/31 / yyyy(年份会有所不同)。到目前为止,这是我的代码:

Sub Test()
    'Prompt users to input a new quarter-end date and validate that the date is the last day of a calendar quarter-end


Do

'Prompts users for a date
    InpDT = InputBox("Enter quarter-end date (mm/dd/yyyy): ", "Quarter-End Date")


'Validates proper date format
    If Not IsDate(InpDT) Then
        MsgBox "Invalid date format"
        valid = False

'Validates that month of date is either March, June, September, or December
    ElseIf IsError(Application.Match(DatePart("m", InpDT), Array(3, 6, 9, 12), False)) Then
        MsgBox "Must be quarter-end month (i.e. 'March')"
        valid = False

'Validates that day of date is 31 for March/December or 30 for June/September
    ElseIf Not ((IsError(Application.Match(DatePart("m", InpDT), Array(6, 9), False)) And IsError(Application.Match(DatePart("d", InpDT), Array(30), False))) Or (IsError(Application.Match(DatePart("m", InpDT), Array(3, 12), False)) And IsError(Application.Match(DatePart("d", InpDT), Array(31), False)))) Then
        MsgBox "Must be last day of quarter-end (i.e. 'March 31')"
        valid = False

    Else
        AsOf = DateValue(InpDT)
        valid = True
    End If
    Loop Until valid = True
End Sub

在最后一个ElseIf子句之前,该子项似乎可以正常工作,在这里我要确保如果用户输入的月份为6月或9月,则日期必须为“ 30”,而如果用户输入的月份为3月或12月,天必须为“ 31”。目前,sub确认3/6/9/12个月内的任何一天有效(即不拒绝“ 3/29/2018”)。

任何帮助将不胜感激(相对于VBA而言是新的。)

0 个答案:

没有答案