如何检查读入VBA日期的空字段

时间:2018-05-03 14:34:04

标签: excel vba

我有一个VBA日期变量读取并取得Excel中字段的值:

dim myDate as Date
myDate = MySheet.Range("A1").Value

现在,如果A1为空,我打印了myDate的值,它给了我

12:00:00 AM

如何在IF声明中检查?如在,我该怎么替换???以下:

if myDate = ??? then
    MsgBox ("There is nothing in the field")
Else
    MsgBox (myDate)
End If

4 个答案:

答案 0 :(得分:4)

如果您要测试myDate,则应将其声明为Variant

类型
Dim myDate As Variant
myDate = [a1]

If Not IsDate(myDate) Then
    MsgBox "There is no date in the field"
Else
    MsgBox myDate
End If

或者,您可以测试[a1]以查看它是否包含任何内容。

答案 1 :(得分:2)

日期实际上只是Double的一个子集,带有字符串表示。

不要打扰字符串转换,无论如何日期都不是字符串。

12:00:00 AMDate的字符串表示形式,其值为0,因此最简单的方法是与0进行比较。

但是,在没有先验证单元格值的情况下,将单元格值直接存储到Date变量(或者除了Variant之外的其他任何变量),会让您对类型不匹配开放您尝试将某些#VALUE!错误转换为日期,字符串或数字的那一天出现错误 - 在读取单元格值时,您需要避免显式的隐式类型转换,并使用Variant

Dim cellValue As Variant
cellValue = Range("A1").Value

从现在开始,如果无法进行转换,任何采用类型的操作都会抛出类型不匹配

由于我们需要Date,让我们使用IsDate函数来验证类型:

Dim dateValue As Date
If IsDate(cellValue) Then
    dateValue = CDate(cellValue)
Else
    ' not a date
End If

答案 2 :(得分:1)

使用以下2之一:

  • .container { width:10px; --container-width: width; box-shadow: 0 0 0 calc(var(--container-width) * 0.1) rgba(0,0,0,0.1); }

  • If Len(Trim(myDate)) > 0 Then

请确保您写:

  • If Trim(myDdate) = vbNullString Then

  • If myDate = Null Then

Dim myDate as Date : IsEmpty(myDate) Then始终返回False,因为IsEmpty(myDate)被声明为myDate而不是DateVariant仅适用于IsEmpty(),因为只有Variant可以Variant

答案 3 :(得分:1)

您可以使用变体:

Sub datetest()
    Dim mysheet As Worksheet
    Dim myDate As Variant

    Set mysheet = ActiveSheet
    myDate = mysheet.Range("A1").Value
    If myDate = "" Then
        MsgBox "A1 is empty"
    Else
        myDate = CDate(myDate)
        MsgBox myDate
    End If
End Sub