VBA如果设置变量如何检查变量?

时间:2017-08-24 20:56:26

标签: vba ms-office

我尝试在第一次调用函数时将静态变量设置为1。怎么做正确?这是类型不匹配错误。

 Static clip_success As Integer
 If clip_success Is Nothing Then
    clip_success = 1
 End If

1 个答案:

答案 0 :(得分:4)

任何原始值类型都将使用其默认值进行初始化。对于值为0的数字类型;对于字符串,""(空字符串);对于约会,1899-12-30Boolean初始化为False

你的静态变量看起来非常像一个标志 - 应该是Boolean

使用特殊值Variant初始化Empty

使用Nothing / null引用初始化任何对象引用。

所以:

Static clip_success As Long
If clip_success = 0 Then
   clip_success = 1
End If

或者

Static clip_success As Date
If clip_success = CDate(0) Then
   clip_success = DateTime.Now
End If

或者

Static clip_success As String
If clip_success = vbNullString Then
   clip_success = "success!"
End If

或者

Static clip_success As Variant
If IsEmpty(clip_success) Then
   clip_success = 1
End If

或者

Static clip_success As Object
If clip_success Is Nothing Then
   Set clip_success = New [some class]
End If
相关问题