The VBA CSng Function

Description

The VBA CSng function converts an expression into a Single data type (i.e. into a single precision floating point number).

The syntax of the function is:

CSng( Expression )

Where the Expression argument is the expression that that you want to convert to a Single data type.


VBA CSng Function Examples

The following VBA code shows how the CSng function can be used to convert text strings and numeric values into single precision floating point numbers.

' Convert strings and numeric values into Singles
Dim sng1 As Single
Dim sng2 As Single
Dim sng3 As Single
sng1 = CSng( "0.66666666" )
' sng1 is now equal to 0.6666667
sng2 = CSng( "235.1111111" )
' sng2 is now equal to 235.1111
sng3 = CSng( 1.01 * 1.01 )
' sng3 is now equal to 1.0201

After running the above VBA code, the variables sng1, sng2 and sng3 are equal to 0.6666667, 235.1111 and 1.0201 respectively

Note that the values 0.66666666 and 235.1111111 have been rounded up or down, to convert them to single precision floating point numbers.


VBA CSng Function Error

If the CSng function is supplied with a text string that cannot be converted to a numeric value, it will return the error:

Run-time error '13': Type mismatch

VBA Run Time Error 13 Message Box