Converting - Implicit

An implicit data type conversion is a conversion that happens automatically. Widening casts are often implicit.
VBA provides implicit conversion for a large number of data types


Integer to Long

Dim myInteger As Integer 
Dim myLong As Long
myInteger = 10
myLong = myInteger
Debug.Print myLong // 10

Integer to Boolean

All numeric data types can be converted to boolean.
When converting a numeric VBA data type into a Boolean, 0 becomes FALSE and all other values (regardless of whether they're negative or positive) become TRUE.

Dim myInteger As Integer 
Dim myBool As Boolean
myInteger = 10
myBoolean = myInteger
Debug.Print myBool // True (<>0) False (0)

Integer to String

Dim myInteger As Integer 
Dim myString As String
myInteger = 14
myString = myInteger
Debug.Print myString // "14"

Double to Integer

Dim myDouble As Double 
Dim myInteger As Integer
myDouble = 10.6
myInteger = myDouble
Debug.Print myInteger // 11

Double to String

Dim myDouble As Double 
Dim myString As String
myDouble = 10.6
myString = myDouble
Debug.Print myString // "10.6"

Boolean to Integer

When converting a Boolean variable to a numeric VBA data type, TRUE becomes -1 and FALSE becomes 0.

Dim myBool As Boolean 
Dim myInteger As Integer
myBool = True
myInteger = myBool
Debug.Print myInteger // -1 (True) 0 (False)

String to Long

Strings that contain numerical values can be converted to numbers.

Dim myString As String 
Dim myLong As Long
myString = "10"
myLong = myString
Debug.Print myLong // 10

String to Boolean

Strings that contain boolean values can be converted to booleans.

Dim myString As String 
Dim myBoolean As Boolean
myString = "True"
myBoolean = myString
Debug.Print myBoolean // True

Long to Integer - Overflow

If an implicit conversion is not possible you will get an overflow error
SS

Dim myLong As Long 
Dim myInteger As Integer
myLong = 100000
myInteger = myLong

Variant Data Type

When a variable is declared as a Variant data type all the conversions are done implicitly.
show examples


© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext