Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null values for variables in VBA

Tags:

How do I define a Null string, date or integer in VBA?

I need to be able to assign a Null value to some fields for certain records when data is incomplete or irrelevant, but if I declare a variable as a String, Date or Integer, I get errors when trying to assign a Null value.

Is the only solution to use Variant? If so, then what is the point of all other datatypes in VBA?

like image 939
HorusKol Avatar asked Apr 12 '11 05:04

HorusKol


People also ask

How do you assign a null value to a variable in VBA?

This keyword cannot be assigned to variables of other data types. The Null data type can be assigned explicitly to indicate that the variable has no data. A Null value is normally used to indicate an invalid value or error. The Null data type can only be assigned explicitly.

How do you handle null values in VBA?

This example uses the IsNull function to determine if a variable contains a Null. Dim MyVar, MyCheck MyCheck = IsNull(MyVar) ' Returns False. MyVar = "" MyCheck = IsNull(MyVar) ' Returns False. MyVar = Null MyCheck = IsNull(MyVar) ' Returns True.

What is a null value in VBA?

In VBA, Null keyword is used to indicate that a variable contains no valid data. A value indicating that a variable contains no valid data. Null is the result - (i) if you explicitly assign Null to a variable, or (ii) if you perform any operation between expressions that contain Null.

How do you declare a variable null?

You can assign null to a variable to denote that currently that variable does not have any value but it will have later on. A null means absence of a value. In the above example, null is assigned to a variable myVar. It means we have defined a variable but have not assigned any value yet, so value is absence.


1 Answers

Dim x As Variant x = Null 

Only the Variant data type can hold the value Null.

A Variant is a special data type that can contain any kind of data [...] A Variant can also contain the special values Empty, Error, Nothing, and Null.

The "point" of all the other data types is precisely that they cannot contain any ol' kind of data. This has two advantages that I can think of:

  • It's more difficult for the programmer to assign data of an unintended type to the variable by mistake, since this will be detected at compile time. This can help prevent bugs and make things clearer for you and the next person who will be maintaining your code.
  • Narrow data types save storage space. Putting integers in a Variant (16 bytes) takes up way more memory than putting them in an Int (2 bytes). This becomes significant if you have large arrays.

Of course, Variants do have their place, as other threads on this site discuss.

like image 93
Jean-François Corbett Avatar answered Sep 29 '22 12:09

Jean-François Corbett