How to convert string to double in vba?

In Visual Basic for Applications (VBA), the CDbl() function can be used to convert a string to a double data type. This requires the string to contain a valid numeric representation of a number. The string can be a number in the form of a literal or a variable. The CDbl() function will return the number as a double data type. It is important to note that if the string is not a valid number, the CDbl() function will return an error.


You can use the CDbl function in VBA to convert a text string to a double data type.

Here is a common way to use this function in practice:

Sub ConvertStringToDouble()

    Dim i As Integer

    For i = 2 To 11
        If IsNumeric(Range("A" & i)) Then
            Range("B" & i) = CDbl(Range("A" & i))
        Else
            Range("B" & i) = 0
        End If
    Next i

End Sub

This particular macro will convert each string in the range A2:A11 to a double data type only if the string is a number.

Otherwise, the string will be converted to a value of zero.

The following example shows how to use this syntax in practice.

Example: Convert String to Double in VBA

Suppose we have the following column of values in Excel that are currently formatted as text strings:

Suppose we would like to convert each string to a double data type only if the string is a number and display them in column B.

We can create the following macro to do so:

Sub ConvertStringToDouble()

    Dim i As Integer

    For i = 2 To 11
        If IsNumeric(Range("A" & i)) Then
            Range("B" & i) = CDbl(Range("A" & i))
        Else
            Range("B" & i) = 0
        End If
    Next i

End Sub

When we run this macro, we receive the following output:

Notice that only the text strings in column A that are numbers are converted to double data types in column B.

Otherwise, the text strings are simply converted to a value of zero.

Note: You can find the complete documentation for the VBA CDbl function .

x