What is CStr function in VBA
The CStr function is used to convert a value to a string.
It takes an expression as an argument i.e.
The examples below show the usage of CStr function.
An example of converting an Integer to String by CStr
We have an integer type variable and assign it a value. Then we used CStr function to convert it to a string.
Sub cstr_ex() Dim num As Integer Dim str As String num = 100 str = CStr(num) End Sub
Convert a Single variable (with a decimal number) to String
Similarly, you may convert a decimal number to a string by CStr function. The following VBA program shows:
Sub cstr_ex() Dim dec As Single Dim str As String dec = 100.55 str = CStr(dec) End Sub
Converting date to string example
Sub cstr_ex() Dim dt As Date Dim str As String dt = #10/10/2019# str = CStr(dt) MsgBox (str) End Sub
Converting cell values to String example
A date variable value is converted to a string and displayed in a message box by CStr function:
Sub cstr_ex() Dim dt As Date Dim str As String dt = #10/10/2019# str = CStr(dt) MsgBox ("After Date to String Conversion: " & str) End Sub
Output:
Using Excel cell numbers and writing in another cell after conversion
We will use the A2 and A3 cells’ values (that contain numbers) in the CStr function and write the converted value to the B2 and B3 cells.
Sub cstr_ex() Range("B2").Value = CStr(Range("A2").Value) Range("B3").Value = Range("A3").Value End Sub
Output:
Writing different values to cells after conversion by CStr
In this example, we have a number, a decimal number, a string, text with a number, and date in A2 to A5 cells.
We used a for loop to iterate through all cells and assign the respective values to B cells after conversion by the CStr function.
See the code and output:
Sub cstr_ex() Dim i For i = 2 To 6 Range("B" & i).Value = CStr(Range("A" & i).Value) Next i End Sub
Output: