验证日期格式

时间:2016-06-01 09:54:44

标签: vba excel-vba excel

任何人都知道如何以mm/dd/yyyy的格式验证日期格式。 我试过这段代码但是没有用。

在userform中:

dateCheck (txtStartDate)

在模块中:

Function dateCheck(dateValue As Date) As Boolean
    If CDate(dateValue) <> "mm/dd/yyyy" Then
        MsgBox "Please use the mm/dd/yyyy  date format!"
        dateCheck = True
    End If
End Function

我是否在正确的轨道上?谢谢!

3 个答案:

答案 0 :(得分:1)

您的功能的CDate(dateValue)部分只会返回&#39; dateValue&#39;作为Date。使用.Numberformat属性获取格式:

Function dateCheck(dateValue As Date) As Boolean
    If dateValue.NumberFormat <> "mm/dd/yyyy" Then
        MsgBox "Please use the mm/dd/yyyy  date format!"
        dateCheck = True
    End If
End Function

答案 1 :(得分:1)

问题是你的问题更复杂了。您的问题实际上涉及两个步骤:

  1. txtStartDate实际上是有效日期吗?
  2. 如果是日期,是否格式正确?
  3. txtStartDate的命名意味着您将日期作为文本(在表单中)。然而,假设txtStartDate实际上是一个约会,你将它传递给你的函数。这很明显,因为函数dateCheck需要一个日期:Function dateCheck(dateValue As Date) As Boolean

    所以,这是一个解决方案,可以同时解决这两个问题:

    Sub tmpTest()
    
    Dim txtStartDate As String
    
    txtStartDate = "11/20/2015"
    
    Debug.Print dateCheck(txtStartDate)
    
    End Sub
    
    Function dateCheck(dateValue As String) As Boolean
    
    If IIf(IsDate(txtStartDate), Format(CDate(txtStartDate), "mm/dd/yyyy"), "") = dateValue Then dateCheck = True
    
    End Function
    

    请记住,这是一种非常简单的方法,不适用于国际日期格式。事实上,由于我没有您的日期格式,您可能需要稍微调整一下。如果您需要更复杂的东西,那么您将需要编写更多的VBA代码(包括广泛的验证功能)。

答案 2 :(得分:1)

Function dateCheck(dateStrng As String) As Boolean
Dim dateArr as Variant 

If IsDate(dateStrng) Then ' <~~ if it IS a date
   dateArr = Split(dateStrng,"/")
   If UBound(dateArr) = 2 Then '<~~ if it has three substrings separate by two "slashes"
      If CInt(dateArr(0)) < 13 Then  '<~~ if the 1st number is lower or equals the maximum possible month number
         If CInt(dateArr(0)) > 0 Then  '<~~ if the 1st number is higher or equals the mimimum possible month number
            If CInt(dateArr(1)) < 31 Then  '<~~ if the 2nd number is lower or equals the maximum possible day number
               If CInt(dateArr(1)) > 0 Then  '<~~ if the 2nd number is higher or equals the mimimum possible day number
                  If CInt(dateArr(2)) < 10000 Then dateCheck = CInt(dateArr(2)) > 999  '<~~ if the 3rd number is a 4 digit integer "year" number, then check returns True
               End If
            End If
         End If
      End If
   End If
End Function