Vba excel value as string

Use Range("A1").Text instead of .Value

post comment edit:
Why?
Because the .Text property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92 then <- Text will return exactly what it in the cell including any formatting.
The .Value and .Value2 properties return what’s stored in the cell under the hood excluding formatting. Specially .Value2 for date types, it will return the decimal representation.

If you want to dig deeper into the meaning and performance, I just found this article which seems like a good guide

another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
Dont Format column A, Format B as TEXT, C as Date, D as Percentage
now,
paste this code in a module

Sub main()

    Dim ws As Worksheet, i&, j&
    Set ws = Sheets(1)
    For i = 3 To 7
        For j = 1 To 4
            Debug.Print _
                    "row " & i & vbTab & vbTab & _
                    Cells(i, j).Text & vbTab & _
                    Cells(i, j).Value & vbTab & _
                    Cells(i, j).Value2
        Next j
    Next i
End Sub

and Analyse the output! Its really easy and there isn’t much more i can do to help :)

            .TEXT              .VALUE             .VALUE2
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 4       1                 1                   1
row 4       1                 1                   1
row 4       01/01/1900        31/12/1899          1
row 4       1.00%             0.01                0.01
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 6       63                63                  63
row 6       =7*9              =7*9                =7*9
row 6       03/03/1900        03/03/1900          63
row 6       6300.00%          63                  63
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013        29/05/2013          29/05/2013
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013%       29/05/2013%         29/05/2013%

In this Article

  • String Variable Type
    • Fixed String Variable
  • Declare String Variable at Module or Global Level
    • Module Level
    • Global Level
  • Convert Values stored as String
  • Convert String Stored as Values

String Variable Type

The String data type is one of the most common data types in VBA. It stores “strings” of text.

To declare an variable String variable, you use the Dim Statement (short for Dimension):

Dim strName as String

To assign a value to a variable, you use the equal sign:

strName = "Fred Smith"

Putting this in a procedure looks like this:

Sub strExample()
'declare the string
   Dim strName as string
'populate the string
    strName = "Fred Smith"
'show the message box
   MsgBox strname
End Sub

If you run the code above, the following message box will be shown.

vba string declare

Fixed String Variable

There are actually 2 types of string variables – fixed and variable.

The “variable” string variable (shown in the previous example) allows your string to be any length. This is most common.

The “fixed” string variable defines the size of the string. A fixed string can hold up to 65,400 characters.

Dim strName as string *20

When you define a fixed variable, the number of characters in the variable is locked in place, even if you use fewer characters.

Notice the spaces in the graphic below – the variable has place holders for the rest of the characters in the string as ‘Fred Smith’ is less than 20 characters.

vba string variable size

However, if you have declared a string without specifying the length, then the string will only hold as many characters as are passed to it.

vba string fixed size

Declare String Variable at Module or Global Level

In the previous example, you declared the String variable within a procedure. Variables declared with a procedure can only be used within that procedure.

vba string procedure declare

Instead, you can declare String variables at the module or global level.

Module Level

Module level variables are declared at the top of code modules with the Dim statement.

vba string module declare

These variables can be used with any procedure in that code module.

Global Level

Global level variables are also declared at the top of code modules. However, instead of using the Dim statement, you use the Public statement to indicate that the string variable is available to be used throughout your VBA Project.

Public strName as String

vba string global declare

If  you declared the string variable at a module level and used in a different module, an error would occur.

vba string module error

However, if you use the Public keyword to declare the string variable, the error would not occur and the procedure would run perfectly.

Convert Values stored as String

There may be a time when you have values in Excel that are stored as text – for example, you may have imported a CSV file which may have brought in text instead of numbers.

Note that the value in A1 is left-aligned, indicating a text value.

vba string text

You can use a VBA Function can be used to convert these numbers to text

Sub ConvertValue()
'populate the string
    strQty = Range("A1")
'populate the double with the string
    dblQty = strQty
'populate the range with the number
    Range("A1") = dblQty
End Sub

Once you run the code, the number will move to the right-indicating that it is now stored as a number.

vba string number

This is particularly useful when you loop through a large range of cells.

vba string list

Sub ConvertValue()
    Dim strQty As String, dblQty As Double
    Dim rw As Integer, i As Integer
'count the rows to convert
    rw = Range("A1", Range("A1").End(xlDown)).Rows.Count
'loop through the cells and convert each one to a number
    For i = 0 To rw – 1
'populate the string
        strQty = Range("A1").Offset(i, 0)
'populate the double with the string
        dblQty = strQty
'populate the range with the number
        Range("A1").Offset(i, 0) = dblQty
    Next i
End Sub

The result will be that all the cells are then converted to numbers

vba number list

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!

automacro

Learn More

Convert String Stored as Values

Similarly, there might be values that you need to convert from a string to a value – for example, if you require a leading zero on a telephone number.

vba string number to string

Sub ConvertString()
    Dim strPhone As String, dblPhone As Double
    Dim rw As Integer, i As Integer
'count the rows to convert
    rw = Range("A1", Range("A1").End(xlDown)).Rows.Count
'loop through the cells and convert each one to a number
    For i = 0 To rw – 1
'populate the string
        dblPhone = Range("A1").Offset(i, 0)
'populate the double with the string
        strPhone = "'0" & dblPhone
'populate the range with the number
        Range("A1").Offset(i, 0) = strphone
    Next i
End Sub

vba string number to string converted

Note that you need to  begin the text string with an apostrophe (‘), before the zero in order to tell Excel to enter the value as string.

Функции преобразования типов данных в 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.2643E14

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 для того, чтобы указать, что результатом выполнения той или иной операции должны стать данные определенного типа, отличающегося от типа, заданного по умолчанию.


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

VBA CSTR

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA CSTR (wallstreetmojo.com)

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.

cstr formula

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

cstr example 1.1

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.

cstr example 1.2

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

example 1.3

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 2.2

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

VBA cstr example 3.1

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.

example 3.2

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 CSTR

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.

Syntax of CSTR

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.

VBA CSTR Example 1-1

Step 2: In the VBA editor insert a module from the reference to the screenshot below.

VBA CSTR Example 1-2

Step 3: Double click on the module and let’s begin our macro with a name as shown below.

Code:

Sub sample()

End Sub

VBA CSTR Example 1-3

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

VBA CSTR Example 1-4

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

VBA CSTR Example 1-5

Step 6: Run the code by hitting F5 or Run button and see the output.

Example 1-6

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

VBA CSTR Example 1-7

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

VBA CSTR Example 1-8

Step 9: Re-run the above code and see the last two result as follows.

True Value

The value stored in B is the value of A which is “TRUE”. Now let us see the data type for variable B.

String datatype

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

VBA CSTR Example 2-1

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

Declare two variables Example 2-2

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

VBA CSTR Example 2-3

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

VBA CSTR Example 2-4

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

VBA CSTR Example 2-5

Step 6: Run the code by hitting F5 or Run button and see the output.

Result of Example 2-6

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

VBA CSTR Example 3-1

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

VBA CSTR Example 3-2

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

Store a date in Variable A Example 3-3

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

VBA CSTR Example 3-4

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

VBA CSTR Example 3-5

Step 6: Run the code by hitting F5 or Run button and see the output.

Result of Example 3-6

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 –

  1. VBA Last Row
  2. VBA VLOOKUP
  3. VBA Web Scraping
  4. VBA XML

Понравилась статья? Поделить с друзьями:
  • Vba excel validation описание
  • Vba excel validation add xlvalidatelist
  • Vba excel timer в секундах
  • Vba excel time and date of
  • Vba excel thisworkbook worksheets