我有一个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
答案 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 AM
是Date
的字符串表示形式,其值为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
而不是Date
。 Variant
仅适用于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