Peter
Peter

Reputation: 2181

Difference between "dim a" and "dim a,b"

Strange behaviour of VBA:

This gives an error 94 "Illegal use of Null" in line 3:

Function test1()
  Dim a As String
  a = Null
  test1 = a
End Function

BUT... this works perfectly:

Function test1()
  Dim a, b As String
  a = Null
  test1 = a
End Function

Only difference is the variable b in line 2, which is never used! WTF is going on here?

Upvotes: 3

Views: 471

Answers (1)

HansUp
HansUp

Reputation: 97101

In the second code sample ...

Dim a, b As String

As String applies to only the last variable, b. Variable a is Variant type.

A Variant variable can accept Null. A String variable can not.

In the first code sample, a is explicitly declared as String. That is why it will not accept a Null.

If you want both a and b to be String type, you must explicitly declare the type for each ...

Dim a As String, b As String

Upvotes: 6

Related Questions