If with Variant-type

I have a Variant type which can become to an Integer, a String a Null in my Sub.

I use "If 'variable' Then" and go over the "else" statement to run the source code in case of my 'variable' being "Null".

This works good when 'variable' is an integer - the "if"-clause is "true" - but when 'variable' is a string the error #13 arises (type problem...).

Thanks for your support!
Who is Participating?
caraf_gConnect With a Mentor Commented:
Without looking at your code it is impossible to tell you what's wrong. But here are some tips.

1 Use IsNull
Dim fred As Variant

fred = Null

If IsNull(fred) Then
    MsgBox "it's null"
End If

2 Use vartype
VarType will return a number depending on the type of variable (See help)
vbEmpty      0      Empty (uninitialized)
vbNull      1      Null (no valid data)
vbInteger      2      Integer
vbLong      3      Long integer
vbSingle      4      Single-precision floating-point number
vbDouble      5      Double-precision floating-point number
vbCurrency      6      Currency value
vbDate      7      Date value
vbString      8      String
vbObject      9      Object
vbError      10      Error value
vbBoolean      11      Boolean value
vbVariant      12      Variant (used only with arrays of variants)
vbDataObject      13      A data access object
vbDecimal      14      Decimal value
vbByte      17      Byte value
vbArray      8192      Array

Dim fred As Variant
fred = CDate("1999/11/11")
If VarType(fred) = vbDate Then 'vbDate = 7
    'It's a Date!!
End If

Need any more information? Then don't accept the question until I've answered all your questions.


StapmanAuthor Commented:
Edited text of question.

I'm not sure that I have understood you correctly. Here is an attempt, though. There is an IsNull function that may help. You can also try the IsEmpty function that returns True if the variant variable has not been assigned a value.

If IsNull(x) Then ...

Ture Magnusson
Karlstad, Sweden
Dim Condition As Variant

Condition = 1
If Condition Then MsgBox "True"

Condition = "1"
If CInt(Condition) Then MsgBox "True"

Condition = Null
If IsNull(Condition) Then MsgBox "True"
StapmanAuthor Commented:
Thanks for your quick and detailed answer(s). Thanks to SLE too!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.