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

Double to Integer

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

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)

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 cane be converted to numbers.

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

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