MS-Excel / Functions and Formula

Using the Str Function to Convert a Value to a String

Just as you can convert a string to a numeric value as in the previous section, you can also convert a numeric value to a string. You'll need to do this when you want to concatenate the information contained in a value with a string - if you try to do this simply by using the + operator, VBA attempts to perform the mathematical operation addition rather than the string operation you want: concatenation.

For example, suppose you've declared a String variable named strYourAge and a numeric variable named intAge. You can't use a strYourAge + intAge statement to concatenate them because they're different data types. You first need to create a string from the intAge variable and then concatenate that string with the strYourAge string. (Alternatively, you can use the & operator to concatenate the two variables.)

To convert a value to a string, use the Str function. The syntax for the Str function is this:

Str(number)

Here, number is a variable containing a numeric expression (such as an Integer data type, a Long data type, or a Double data type).

The following short procedure provides an example of converting a value to a string:

Sub Age()
    Dim intAge As Integer, strYourAge As String
    intAge = InputBox("Enter your age:", "Age")
    strYourAge = "Your age is" & Str(intAge) & "."
    MsgBox strYourAge, vbOKOnly + vbInformation, "Age"
End S
[Previous] [Contents] [Next]