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
In this tutorial:
- Using Built-in Functions
- What Is a Function?
- Passing Arguments to a Function
- Using Functions to Convert Data from One Type to Another
- Using the Asc Function to Return a Character Code
- Using the Str Function to Convert a Value to a String
- Using the Format Function to Format an Expression
- Using the Chr Function and Constants to Enter Special Characters in a String
- Using Functions to Manipulate Strings
- Using InStr and InStrRev to Find a String within Another String
- Using LTrim, RTrim, and Trim to Trim Spaces from a String
- Using Len to Check the Length of a String
- Using the StrComp Function to Compare Apples to Apples
- Using VBA's Mathematical Functions
- Excel VBA's Date and Time Functions
- Using the DateDiff Function to Return an Interval
- Using File-Management Functions