Converting other types to strings
Use CStr to convert a numeric type to a string
Section titled “Use CStr to convert a numeric type to a string”Const zipCode As Long = 10012Dim zipCodeText As String'Convert the zipCode number to a string of digit characterszipCodeText = CStr(zipCode)'zipCodeText = "10012"Use Format to convert and format a numeric type as a string
Section titled “Use Format to convert and format a numeric type as a string”Const zipCode As long = 10012Dim zeroPaddedNumber As StringzeroPaddedZipCode = Format(zipCode, "00000000")'zeroPaddedNumber = "00010012"Use StrConv to convert a byte-array of single-byte characters to a string
Section titled “Use StrConv to convert a byte-array of single-byte characters to a string”'Declare an array of bytes, assign single-byte character codes, and convert to a stringDim singleByteChars(4) As BytesingleByteChars(0) = 72singleByteChars(1) = 101singleByteChars(2) = 108singleByteChars(3) = 108singleByteChars(4) = 111Dim stringFromSingleByteChars As StringstringFromSingleByteChars = StrConv(singleByteChars, vbUnicode)'stringFromSingleByteChars = "Hello"Implicitly convert a byte array of multi-byte-characters to a string
Section titled “Implicitly convert a byte array of multi-byte-characters to a string”'Declare an array of bytes, assign multi-byte character codes, and convert to a stringDim multiByteChars(9) As BytemultiByteChars(0) = 87multiByteChars(1) = 0multiByteChars(2) = 111multiByteChars(3) = 0multiByteChars(4) = 114multiByteChars(5) = 0multiByteChars(6) = 108multiByteChars(7) = 0multiByteChars(8) = 100multiByteChars(9) = 0
Dim stringFromMultiByteChars As StringstringFromMultiByteChars = multiByteChars'stringFromMultiByteChars = "World"Remarks
Section titled “Remarks”VBA will implicitly convert some types to string as necessary and without any extra work on the part of the programmer, but VBA also provides a number of explicit string conversion functions, and you can also write your own.
Three of the most frequently used functions are CStr, Format and StrConv.