Return to VBA Code Examples
We have already covered an introduction to string functions in our VBA Strings and Substrings Functions tutorial. In this tutorial, we are going to look at how to convert an integer to a string (click here to learn about converting Strings to Numbers). The reason you would want to convert a number or date to a string is in order to use string manipulation functions on these values.
The VBA CStr Function
The VBA CStr Function allows you to convert a number, date or boolean data type to a string.
MsgBox CStr (88)
The syntax of the CStr Function is:
CStr(expression) where expression is the number or date that you want to convert.
The following code shows you how numbers are outputted compared to text, including by using the CStr Function.
Sub UsingTheConvertToStringFunction()
Debug.Print CStr(8)
Debug.Print "Text"
Debug.Print 8
Debug.Print 2
End Sub
This uses Debug.Print to output the results to the Immediate Window.
Both CStr(8) and the word Text are displayed as text and are left aligned whereas the two numbers are right aligned within the immediate window.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!
Excel VBA CSTR Function
CSTR in VBA is a data type conversion function that one may use to convert any value provided to this function to a string. For example, even if the given input is an integer or float value, this function will convert the value’s data type to a string data type, so the return type of this function is a string.
How do we go about this if we need to convert any value to string data type in VBAData type is the core character of any variable, it represents what is the type of value we can store in the variable and what is the limit or the range of values which can be stored in the variable, data types are built-in VBA and user or developer needs to be aware which type of value can be stored in which data type. Data types assign to variables tells the compiler storage size of the variable.read more? For this, in VBA, we have a function called “CSTR.” In this article, we will guide you through the methodology of the “CSTR” function in VBA.
The String is the data type that holds any String values. When we say string, it generally refers to text values, but that is not true with VBA codingVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more. A string can hold any order of characters as data. For example, “Hello” is treated as String, “123456” is treated as a string and “12-04-2019” as a string. This String data type can hold any order of characters.
Table of contents
- Excel VBA CSTR Function
- What Does CSTR Function Do in VBA?
- VBA CSTR Syntax
- How to Use VBA CSTR Function in Excel?
- Example #1
- Example #2
- Example #3
- Recommended Articles
- What Does CSTR Function Do in VBA?
What Does CSTR Function Do in VBA?
Have you ever thought of converting a different expression to Strings in VBAString functions in VBA do not replace the string; instead, this function creates a new string. There are numerous string functions in VBA, all of which are classified as string or text functions.read more? If you have a doubt, is that possible? Then the answer is an absolute YES!
CSTR is a function covering different format expressions to String format in VBA. With the CSTR function, we can convert the provided expression value to the String data type.
VBA CSTR Syntax
Below is the syntax of the Excel VBA CSTR function.
The syntax of the CSTR function includes only one argument.
Expression: It is the targeted value or cell value we are trying to change to the String data type.
The value could be any data type. So, CSTR goes ahead and converts to String data type. The common data types we usually convert are Integer, Boolean, and Date to String data types.
How to Use VBA CSTR Function in Excel?
Now, we will see some examples of the Excel VBA CSTR function.
You can download this VBA CStr Excel Template here – VBA CStr Excel Template
Example #1
Look at the below code.
Code:
Sub CSTR_Example1() Dim NumericValue As Integer Dim StringResult As String NumericValue = 855 StringResult = CStr(NumericValue) MsgBox StringResult End Sub
Firstly, we assigned the Integer data type to the variable “NumericValue” as 855. Now, the variable “NumericValue” holds the Integer data type. Another variable, “StringResult,” assigned the formula CSTR to convert Integer data type to String data type.
CSTR converted the integer number to String data type. So, even though we can see the number 855, it is no longer an Integer Date Type in VBAIn VBA, an integer is a data type that may be assigned to any variable and used to hold integer values. In VBA, the bracket for the maximum number of integer variables that can be kept is similar to that in other languages. Using the DIM statement, any variable can be defined as an integer variable.read more. Instead, it is now in the String data type.
Example #2
Look at an example of VBA Boolean Data TypeBoolean is an inbuilt data type in VBA used for logical references or logical variables. The value this data type holds is either TRUE or FALSE and is used for logical comparison. The declaration of this data type is similar to all the other data types.read more Conversion.
Code:
Sub CSTR_Example2() Dim Val1 As Boolean Dim Val2 As Boolean Val1 = True Val2 = False MsgBox CStr(Val1) & vbNewLine & CStr(Val2) End Sub
In the above code, I have declared two variables as Boolean.
Dim Val1 As Boolean Dim Val2 As Boolean
In the next line, we have assigned Boolean values as TRUE and FALSE.
Val1 = True Val2 = False
At this point, both variables are Boolean data types. Therefore, we have applied the VBA CSTR function in this example to convert this Boolean data type to a String data type.
Example #3
Look at the example of Date data type conversion to String data type.
Code:
Sub CSTR_Example3() Dim Date1 As Date Dim Date2 As Date Date1 = #10/12/2019# Date2 = #5/14/2019# MsgBox CStr(Date1) & vbNewLine & CStr(Date2) End Sub
We have declared two variables as Date.
Dim Date1 As Date Dim Date2 As Date
Next line, we have assigned the Date values as 10-12-2019 and 05-14-2019, respectively.
Date1 = #10/12/2019# Date2 = #5/14/2019#
At this point, both the variables are Date data types. In the next line, we have applied the CSTR function to convert the Date data type to the String data type. Like CSTR function used to convert any other data type to String data type.
Recommended Articles
This article has been a guide to VBA CStr. Here, we learn how to use the VBA CStr function to convert the value to String data type, along with some simple to advanced examples. Below are some useful Excel articles related to VBA: –
- Convert String in VBA
- Excel VBA StrComp
- VBA Like Operator
- Count Function in VBA
Функции преобразования типов данных в VBA Excel. Наименования функций, синтаксис, типы возвращаемых данных, диапазоны допустимых значений выражения-аргумента.
Синтаксис функций преобразования
Выражение (аргумент) – это любое строковое или числовое выражение, возвращающее значение, входящее в диапазон допустимых значений для аргумента. Выражение может быть представлено переменной или другой функцией.
Если аргумент, переданный в функцию, не входит в диапазон типа, в который преобразуются данные, происходит ошибка.
Функции преобразования типов
Наименования функций преобразования типов, типы возвращаемых данных, диапазоны допустимых значений для аргумента:
Функция | Тип данных | Диапазон значений аргумента |
---|---|---|
CBool | Boolean | Любое допустимое строковое или числовое выражение. |
CByte | Byte | От 0 до 255. |
CCur | Currency | От -922 337 203 685 477,5808 до 922 337 203 685 477,5807. |
CDate | Date | Любое допустимое выражение даты. |
CDbl | Double | От -1,79769313486231E308 до -4,94065645841247E-324 для отрицательных значений; от 4,94065645841247E-324 до 1,79769313486232E308 для положительных значений. |
CDec | Decimal | 79 228 162 514 264 337 593 543 950 335 для чисел без десятичных знаков. Для чисел с 28 десятичными знаками диапазон составляет 7,9228162514264337593543950335. Наименьшим возможным числом, отличным от нуля, является число 0,0000000000000000000000000001. |
CInt | Integer | От -32 768 до 32 767, дробная часть округляется. |
CLng | Long | От -2 147 483 648 до 2 147 483 647, дробная часть округляется. |
CSng | Single | От -3,402823E38 до -1,401298E-45 для отрицательных значений; от 1,401298E-45 до 3,402823E38 для положительных значений. |
CStr | String | Результат, возвращаемый функцией CStr, зависит от аргумента Выражение. |
CVar | Variant | Диапазон совпадает с типом Double для числовых значений и с типом String для нечисловых значений. |
Дополнительно для VBA7:
Функция | Тип данных | Диапазон значений аргумента |
---|---|---|
CLngLng | LongLong | От -9 223 372 036 854 775 808 до 9 223 372 036 854 775 807, дробная часть округляется. Действительно только для 64-разрядных платформ. |
CLngPtr | LongPtr | От -2 147 483 648 до 2 147 483 647 для 32-разрядных платформ, от -9 223 372 036 854 775 808 до 9 223 372 036 854 775 807 для 64-разрядных платформ, дробная часть округляется в обоих типах систем. |
Примеры преобразования типов
Функция CBool
Функция CBool используется для преобразования выражений в тип данных Boolean.
Dim a a = CBool(10) ‘Результат: True a = CBool(0) ‘Результат: False a = CBool(«True») ‘Результат: True a = CBool(«Test») ‘Результат: Error Dim a, b, c a = «Test1» b = «Test2» c = CBool(a = b) ‘Результат: False c = CBool(a <> b) ‘Результат: True |
Функция CByte
Функция CByte используется для преобразования выражений в тип данных Byte.
Dim a, b, c a = 654 b = 3.36 c = a / b ‘Результат: 194,642857142857 c = CByte(c) ‘Результат: 195 c = a * b ‘Результат: 2197,44 c = CByte(c) ‘Результат: Error |
Функция CCur
Функция CCur используется для преобразования выражений в тип данных Currency.
Dim a, b, c a = 254.6598254 b = 569.2156843 c = a + b ‘Результат: 823,8755097 c = CCur(a + b) ‘Результат: 823,8755 |
Функция CDate
Функция CDate используется для преобразования выражений в тип данных Date. Она распознает форматы даты в соответствии с национальной настройкой системы.
Dim a As String, b As Date, c As Double a = «28.01.2021» b = CDate(a) ‘Результат: #28.01.2021# c = CDbl(b) ‘Результат: 44224 Dim a a = CDate(44298.63895) ‘Результат: #12.04.2021 15:20:05# a = CDate(44298) ‘Результат: #12.04.2021# a = CDate(0.63895) ‘Результат: #15:20:05# |
Функция CDbl
Функция CDbl используется для преобразования выражений в тип данных Double.
Dim a As String, b As String, c As Double a = «45,3695423» b = «548955,756» c = CDbl(a) + CDbl(b) ‘Результат: 549001,1255423 |
Примечание
Eсли основной язык системы – русский, при записи в редакторе VBA Excel дробного числа в виде текста, ставим в качестве разделителя десятичных разрядов – запятую. Проверьте разделитель по умолчанию для своей национальной системы:
MsgBox Application.DecimalSeparator
Функция CDec
Функция CDec используется для преобразования выражений в тип данных Decimal.
Dim a As String, b As Double, c a = «5,9228162514264337593543950335» b = 5.92281625142643 c = CDec(a) — CDec(b) ‘Результат: 0,0000000000000037593543950335 Dim a As Double, b As String, c a = 4.2643E—14 b = CStr(a) ‘Результат: «4,2643E-14» c = CDec(a) ‘Результат: 0,000000000000042643 |
Функция CInt
Функция CInt используется для преобразования выражений в тип данных Integer.
Dim a As String, b As Integer a = «2355,9228» b = CInt(a) ‘Результат: 2356 |
Функция CLng
Функция CLng используется для преобразования выражений в тип данных Long.
Dim a As Date, b As Long a = CDate(44298.63895) ‘Результат: #12.04.2021 15:20:05# b = CLng(a) ‘Результат: 44299 a = CDate(b) ‘Результат: #13.04.2021# |
Функция CSng
Функция CSng используется для преобразования выражений в тип данных Single.
Dim a As String, b As Single a = «3,2365625106» b = CSng(a) ‘Результат: 3,236562 |
Функция CStr
Функция CStr используется для преобразования выражений в тип данных String.
Dim a As Single, b As String a = 5106.23 b = CStr(a) ‘Результат: «5106,23» |
Функция CVar
Функция CVar используется для преобразования выражений в тип данных Variant.
Dim a As Double, b As String, c a = 549258.232546 b = «Новое сообщение» c = CVar(a) ‘Результат: 549258,232546 (Variant/Double) c = CVar(b) ‘Результат: «Новое сообщение» (Variant/String) |
Функции преобразования типов данных используются в тексте процедур VBA Excel для того, чтобы указать, что результатом выполнения той или иной операции должны стать данные определенного типа, отличающегося от типа, заданного по умолчанию.
VBA CStr Function in Excel is categorized as a Data Type Conversion function. It is a built-in function in Excel VBA. This VBA CStr function converts an expression to a String data type.
This function can use in either procedure or function in a VBA editor window in Excel. We can use this CStr Function in Excel VBA any number of times in any number of procedures or functions. In the following section you learn many topics. Like what is the syntax and parameters of the CStr function, where we can use this CStr Function and it’s real-time examples.
Table of Contents:
- Objective
- Syntax of VBA CStr Function
- Parameters or Arguments
- Where we can apply or use VBA CStr Function?
- Example 1: Convert a String(100) to String Data Type
- Example 2: Convert a Value(12345.678) to String Data Type
- Example 3: Convert a Value(True) to String Data Type
- Example 4: Convert a Value(False) to String Data Type
- Instructions to Run VBA Macro Code
- Other Useful Resources
The syntax of the CStr Function in VBA is
CStr(Expression)
The CStr function returns a string data type value.
Parameters or Arguments:
The CStr function has one argument in Excel VBA.
where
Expression:It is a mandatory argument. An expression argument represents a value. It is used to convert the value to a string value.
Where we can apply or use CStr Function in Excel VBA?
We can use this CStr Function in VBA MS Office 365, MS Excel 2016, MS Excel 2013, 2011, Excel 2010, Excel 2007, Excel 2003, Excel 2016 for Mac, Excel 2011 for Mac, Excel Online, Excel for iPhone, Excel for iPad, Excel for Android tablets and Excel for Android Mobiles.
Example 1: Convert a String(100) to String Data Type
Here is a simple example of the CStr function in Excel VBA. This below example specified an expression(100) converts to a string type value.
'Convert a String(100) to String Data Type Sub VBA_CStr_Function_Ex1() 'Variable declaration Dim sValue As String Dim dResult As String sValue = 100 dResult = CStr(sValue) MsgBox "String(100) to String Data Type : " & dResult, vbInformation, "VBA CStr Function" End Sub
Output: Here is the screen shot of the first example output.
Example 2: Convert a Value(12345.678) to String Data Type
Here is a simple example of the CStr function in Excel VBA. This below example specified an expression(12345.678) converts to a string type value.
'Convert a Value(12345.678) to String Data Type Sub VBA_CStr_Function_Ex2() 'Variable declaration Dim sValue As Double Dim dResult As String sValue = 12345.678 dResult = CStr(sValue) MsgBox "Value(12345.678) to String Data Type : " & dResult, vbInformation, "VBA CStr Function" End Sub
Output: Here is the screen shot of the second example output.
Example 3: Convert a Value(True) to String Data Type
Here is a simple example of the CStr function using VBA in Excel. This below example specified an expression(True) converts to a string type value. It returns true as output.
'Convert a Value(True) to String Data Type Sub VBA_CStr_Function_Ex3() 'Variable declaration Dim sValue Dim dResult As String sValue = True dResult = CStr(sValue) MsgBox "Value(True) to String Data Type : " & dResult, vbInformation, "VBA CStr Function" End Sub
Output: Here is the screen shot of the third example output.
Example 4: Convert a Value(False) to String Data Type
Here is a simple example of the CStr function in Excel using VBA. This below example specified an expression(False) converts to a string type value. It returns false as output.
'Convert a Value(False) to String Data Type Sub VBA_CStr_Function_Ex4() 'Variable declaration Dim sValue Dim dResult As String sValue = False dResult = CStr(sValue) MsgBox "Value(False) to String Data Type : " & dResult, vbInformation, "VBA CStr Function" End Sub
Output: Here is the screen shot of the fourth example output.
List of All Type Conversion Functions in Excel VBA:
Here are the list of Data Type Conversion functions. And also find its syntax and return type. Please click on below link to go and see the related VBA Functions.
Function | Description | Syntax | Return Type |
---|---|---|---|
VBA CBool | VBA CBool function converts an expression to a Boolean data type. | CBool(Expression) | Boolean |
VBA CByte | VBA CByte function converts an expression to a Byte data type. | CByte(Expression) | Byte |
VBA CCur | VBA CCur function converts an expression to a Currency data type. | CCur(Expression) | Currency |
VBA CDate | VBA CDate function converts an expression to a Date data type. | CDate(Expression) | Date |
VBA CDbl | VBA CDbl function converts an expression to a Double data type. | CDbl(Expression) | Double |
VBA CDec | VBA CDec function converts an expression to a Decimal data subtype. | CDec(Expression) | Decimal |
VBA CInt | VBA CInt function converts an expression to an Integer data type. | CInt(Expression) | Integer |
VBA CLng | VBA CLng function converts an expression to a Long data type. | CLng(Expression) | Long |
VBA CSng | VBA CSng function converts an expression to a Single data type. | CSng(Expression) | Single |
VBA CStr | VBA CStr function converts an expression to a String data type. | CStr(Expression) | String |
VBA CVar | VBA CVar function converts an expression to a Variant data type. | CVar(Expression) | Variant |
You can use FORMAT function to format the string.
Examples on CStr function in Excel VBA:
VBA Convert Integer To String With Leading Zeros VBA Convert Number To String
Here are few more examples on using cStr function in VBA:
- VBA Type Conversion Functions
- VBA STR Function
- VBA Format Function
Instructions to Run VBA Macro Code or Procedure:
You can refer the following link for the step by step instructions.
Instructions to run VBA Macro Code
Other Useful Resources:
Click on the following links of the useful resources. These helps to learn and gain more knowledge.
VBA Tutorial VBA Functions List VBA Arrays in Excel Blog
VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers
Excel VBA CSTR
We work with lots of conversion function in our work area in excel. Such a function is CSTR function in VBA. It is basically a data type conversion function. So if I said that we want to convert a number to a string how will we do that in VBA? We do this with the help of this VBA CSTR function. VBA CSTR function converts any data type variable to string data type.
Let us learn about VBA CSTR function in detail. VBA CSTR function converts any data type to string type. For example, normally 1234 is a numeric value and ABC is a string value which is pretty simple. But if we want to change the data type for number 1234 from integer to string we use CSTR function. And as said above it is a string conversion function. It takes a single argument in it.
Formula For CSTR function in Excel VBA
Let us look below the formula for CSTR function in VBA.
Now expression can be any data type it could be integer long or Boolean etc. CSTR function will change the data type to String for the given expression regardless of what was the previous data type for the expression of itself. Now let us use this function in a few examples and see how this function actually works.
How to Use Excel VBA CSTR Function?
We will learn how to use a VBA CSTR function with few examples in Excel.
You can download this VBA CSTR Excel Template here – VBA CSTR Excel Template
VBA CSTR – Example #1
For example in true or false results the data type for them is Boolean. But what if we want them to be string data type.
Follow the below steps to use CSTR function in Excel VBA.
Step 1: Open VB Editor from the developer’s tab as shown in the screenshot below.
Step 2: In the VBA editor insert a module from the reference to the screenshot below.
Step 3: Double click on the module and let’s begin our macro with a name as shown below.
Code:
Sub sample() End Sub
Step 4: Declare a variable as data type as Boolean and store value true in it.
Code:
Sub sample() Dim A As Boolean A = True End Sub
Step 5: Let us first display the data type of the variable A using the TypeName Function as follows.
Code:
Sub sample() Dim A As Boolean A = True MsgBox (TypeName(A)) End Sub
Step 6: Run the code by hitting F5 or Run button and see the output.
Step 7: Right now the data type for the variable A is Boolean now let us change it to a string using VBA CSTR function as follows.
Code:
Sub sample() Dim A As Boolean A = True MsgBox (TypeName(A)) Dim B As String B = CStr(A) End Sub
We defined another variable and store the value of A converting it to a string using CSTR function.
Step 8: Now display both the data type of variable B and the value stored in B using the message box function as follows.
Code:
Sub sample() Dim A As Boolean A = True MsgBox (TypeName(A)) Dim B As String B = CStr(A) MsgBox B MsgBox (TypeName(B)) End Sub
Step 9: Re-run the above code and see the last two result as follows.
The value stored in B is the value of A which is “TRUE”. Now let us see the data type for variable B.
Though A had a Boolean value in it we converted it to String using the CSTR function.
VBA CSTR – Example #2
Now let us convert the very basic data type which is an integer in the same way above. Follow the below steps to use CSTR function in Excel VBA.
Step 1: Write another macro name as follows in the same module.
Code:
Sub Sample1() End Sub
Step 2: Declare two variables one as integer and another as a string.
Code:
Sub Sample1() Dim A As Integer Dim B As String End Sub
Step 3: Store any random value in Variable A, keep in mind it is integer data type, so provide an integer value as follows.
Code:
Sub Sample1() Dim A As Integer Dim B As String A = 255 End Sub
Step 4: Now in Variable B convert A to a string using the CSTR function as shown below.
Code:
Sub Sample1() Dim A As Integer Dim B As String A = 255 B = CStr(A) End Sub
Step 5: Let us display the value of variable B as well as the data type of variable B as follows.
Code:
Sub Sample1() Dim A As Integer Dim B As String A = 255 B = CStr(A) MsgBox B MsgBox (TypeName(B)) End Sub
Step 6: Run the code by hitting F5 or Run button and see the output.
The value stored in variable B is 255 which should be an integer but let us see what we get as the data type for variable B, We converted value 255 which was an integer as a string using CSTR function.
VBA CSTR – Example #3
Now let us try a complex data type which is Date data type. We will convert a date data type value to string. Follow the below steps to use CSTR function in Excel VBA.
Step 1: The third macro name can be as follows.
Code:
Sub Sample2() End Sub
Step 2: Two variables need to declare one as Date data type and another as a string as shown in the image below.
Code:
Sub Sample2() Dim A As Date Dim B As String End Sub
Step 3: Store a date in Variable A as follows.
Code:
Sub Sample2() Dim A As Date Dim B As String A = #1/1/2019# End Sub
Step 4: Now convert the date value in A as a string using CSTR function and store the value in variable B as shown below.
Code:
Sub Sample2() Dim A As Date Dim B As String A = #1/1/2019# B = CStr(A) End Sub
Step 5: Now let us display both the value and data type of variable B as follows.
Code:
Sub Sample2() Dim A As Date Dim B As String A = #1/1/2019# B = CStr(A) MsgBox B MsgBox (TypeName(B)) End Sub
Step 6: Run the code by hitting F5 or Run button and see the output.
The value we see above is Date which is stored in variable B but when we press ok we see the data type of the above value. Though the value was the date the data type is a string.
Things to Remember
- CSTR is a conversion function.
- CSTR uses only a single argument.
- VBA CSTR function converts any value of data type to string data type.
Recommended Articles
This is a guide to VBA CSTR Function. Here we discuss how to use Excel VBA CStr function to convert the value to String Data Type along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA Last Row
- VBA VLOOKUP
- VBA Web Scraping
- VBA XML