Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA How to check variable if it is set?

Tags:

ms-office

vba

I try to initiate static variable to be 1 when the function is called first time. How to do it correctly? This is type mismatch error.

 Static clip_success As Integer
 If clip_success Is Nothing Then
    clip_success = 1
 End If
like image 220
John Boe Avatar asked Dec 05 '25 09:12

John Boe


1 Answers

Any primitive value type will be initialized with its default value. For numeric types that value is 0; for strings, that's "" (an empty string); for dates, that's 1899-12-30. A Boolean is initialized to False.

Your static variable looks very much like a flag - should probably be a Boolean.

A Variant is initialized with the special value Empty.

Any object reference is initialized with Nothing / a null reference.


So:

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

Or

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

Or

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

Or

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

Or

Static clip_success As Object
If clip_success Is Nothing Then
   Set clip_success = New [some class]
End If
like image 169
Mathieu Guindon Avatar answered Dec 07 '25 22:12

Mathieu Guindon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!