Converting Numbers
Before trying to convert a string to a number it is a good idea to always make sure that the value is a numerical value.
The ISNUMERIC function will return True or False depending if the value can be evaluated as a number.
String to Integer
The CINT function converts a String to an Integer data type.
Dim sMyString As String
sMyString = "200"
Dim iMyInteger As Integer
If (IsNumeric(sMyString) = True) Then
iMyInteger = CInt(sMyString)
End If
String to Long
The CLNG function converts a String to a Long data type.
Dim sMyString As String
sMyString = "200"
Dim lMyLong As Long
lMyLong = CLng(sMyString)
String to Single
The CSNG function converts a String to a Single data type.
Dim sMyString As String
sMyString = "34.5"
Dim sngMySingle As Single
sngMySingle = CSng(sMyString)
String to Double
The CDBL function converts a String to a Double data type.
Dim sMyString As String
sMyString = "34.5"
Dim dbMyDouble As Double
dbMyDouble = CDbl(sMyString)
String to Decimal
The CDEC function converts a String to a Decimal data type.
Dim sMyString As String
sMyString = "34.5"
Dim dcMyDecimal As Variant
dcMyDecimal = CDec(sMyString)
Decimal to Integer
When you convert a Decimal value to a Long integer value it gets rounded to the nearest integer value.
Digits less than 5 are rounded down
Digits greater than 5 are rounded up
If the digit is 5, then it looks at the digit immediately before the decimal place
1) if its even, its rounded down
2) if its odd, its rounded up
3) if there is no digit, its rounded down
CLng(8.5) = 8 (because 8 is even)
CLng(9.5) - 10 (because 9 is odd)
Dim vdDecimal As Variant
vdMyDecimal = 34.5
Dim iMyInteger
iMyInteger = CInt(vdMyDecimal)
Number to String
The CSTR function converts a Number to a String data type.
Dim sMyString As String
Dim lNumber As Long
lNumber = 400
sMyString = CStr(lNumber)
Debug.Print "My String is " + sMyString
More info Data Types > Converting
More info Numbers > Fixed Point
More info Numbers > Floating Point
© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext