Excel vba целое в строку

Most times, you won’t need to «convert»; VBA will do safe implicit type conversion for you, without the use of converters like CStr.

The below code works without any issues, because the variable is of Type String, and implicit type conversion is done for you automatically!

Dim myVal As String
Dim myNum As Integer

myVal = "My number is: "
myVal = myVal & myNum

Result:

«My number is: 0»

You don’t even have to get that fancy, this works too:

Dim myString as String
myString = 77

«77»

The only time you WILL need to convert is when the variable Type is ambiguous (e.g., Type Variant, or a Cell’s Value (which is Variant)).

Even then, you won’t have to use CStr function if you’re compounding with another String variable or constant. Like this:

Sheet1.Range("A1").Value = "My favorite number is " & 7

«My favorite number is 7»

So, really, the only rare case is when you really want to store an integer value, into a variant or Cell value, when not also compounding with another string (which is a pretty rare side case, I might add):

Dim i as Integer
i = 7
Sheet1.Range("A1").Value = i

7

Dim i as Integer
i = 7
Sheet1.Range("A1").Value = CStr(i)

«7»

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


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.

Converting An Integer To A String in VBA

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!
vba save as

Learn More!

I’m trying to conver a number value to a strin ex. convert 10 to «10»

I tried

    With Range("B2:B" & NewResizeRange)
      .Value = Range("B2:B" & NewResizeRange).Value
      .NumberFormat = "0" ' Or .NumberFormat = "@"
   End With

But it us not converting correctly. Any ideas?

asked Jul 7, 2017 at 7:42

Jordan's user avatar

4

With Range("A1")
    .NumberFormat = "@"
    .Value = .Value
End With

This will make the green triangle for Number stored as text show up and mean that your cell will indeed hold a text value. However, when doing calculations using such a cell as a parameter for the formula, Excel will do some conversion by itself.

If you do not want to use NumberFormat, you could also do:

Range("A1").value = "=""" & Range("A1").value & """" — This creates a formula (If the value was 10, it’ll make a formula ="10") that forces the value to evaluate to a string.

answered Jul 7, 2017 at 8:00

Rik Sportel's user avatar

Rik SportelRik Sportel

2,6511 gold badge14 silver badges23 bronze badges

10

Try selecting your range first. So:

   With Range("B2:B" & NewResizeRange)
      .Value = Range("B2:B" & NewResizeRange).Value
      .Select
      .Selection.NumberFormat = "@"
   End With

Hope this helps.

answered Jul 7, 2017 at 7:57

Roosz0rd's user avatar

3

Convert Integer into String in Excel VBA for Indian Currency in Rupees

Paste this code in macro by creating a module

Function name is ConvertIndianCurrency

   Function ConvertIndianCurrency(ByVal MyNumber)
Dim Temp
Dim Count, DecimalPlace
ReDim Place(9) As String
Place(2) = " Thousand "
Place(3) = " Lakh "
Place(4) = " Crore "
' convert MyNumber to a string, trimming extra spaces.
MyNumber = Trim(Str(MyNumber))
' Find decimal place.
DecimalPlace = InStr(MyNumber, ".")
' If we find decimal place...
If DecimalPlace > 0 Then
    ConvertIndianCurrency = "Please Remove Decimal Places in the Number..."
    Exit Function
End If
Count = 1
If MyNumber <> "" Then
    ' convert last 3 digits of MyNumber to Indian Rupees.
    Temp = ConvertHundreds(Right(MyNumber, 3))
    If Temp <> "" Then
        Rupees = Temp
    End If
    If Len(MyNumber) > 3 Then
        ' Remove last 3 digits from MyNumber.
        MyNumber = Left(MyNumber, Len(MyNumber) - 3)
    Else
        MyNumber = ""
    End If
End If
Do While MyNumber <> ""
    Count = Count + 1
    Temp = ConvertTwoDigits(Right(MyNumber, 2))
    If Temp <> "" Then
        Rupees = Temp & Place(Count) & Rupees
    End If
    If Len(MyNumber) > 2 Then
        ' Remove last 2 converted digits from MyNumber.
        MyNumber = Left(MyNumber, Len(MyNumber) - 2)
    Else
        MyNumber = ""
    End If
Loop
' Clean up Rupees.
Select Case Rupees
    Case ""
        Rupees = "Rupees Nil"
    Case "One"
        Rupees = "Rupee One Only"
    Case Else
        Rupees = "Rupees " & Rupees & " Only"
End Select
ConvertIndianCurrency = Rupees
End Function

Private Function ConvertHundreds(ByVal MyNumber)
Dim Result As String
' Exit if there is nothing to convert.
If Val(MyNumber) = 0 Then
    Exit Function
End If
' Append leading zeros to number.
MyNumber = Right("000" & MyNumber, 3)
' Do we have a hundreds place digit to convert?
If Left(MyNumber, 1) <> "0" Then
    Result = ConvertDigit(Left(MyNumber, 1)) & " Hundred "
End If
' Do we have a tens place to convert?
If Mid(MyNumber, 2) <> "0" Then
    Result = Result & ConvertTens(Mid(MyNumber, 2))
Else
    ' If not, then convert the ones place digit.
    Result = Result & ConvertDigit(Mid(MyNumber, 3))
End If
ConvertHundreds = Trim(Result)
End Function

Private Function ConvertTwoDigits(ByVal MyNumber)
Dim Result As String
' Exit if there is nothing to convert.
If Val(MyNumber) = 0 Then
    Exit Function
End If
' Append leading zeros to number.
MyNumber = Right("00" & MyNumber, 2)
' Do we have a tens place to convert?
If Left(MyNumber, 1) <> "0" Then
    Result = ConvertTens(Mid(MyNumber, 1))
Else
    Result = Result & ConvertDigit(Right(MyNumber, 1))
End If
ConvertTwoDigits = Trim(Result)
End Function

Private Function ConvertTens(ByVal MyTens)
Dim Result As String
' Is value between 10 and 19?
If Val(Left(MyTens, 1)) = 1 Then
    Select Case Val(MyTens)
        Case 10: Result = "Ten"
        Case 11: Result = "Eleven"
        Case 12: Result = "Twelve"
        Case 13: Result = "Thirteen"
        Case 14: Result = "Fourteen"
        Case 15: Result = "Fifteen"
        Case 16: Result = "Sixteen"
        Case 17: Result = "Seventeen"
        Case 18: Result = "Eighteen"
        Case 19: Result = "Nineteen"
        Case Else
    End Select
Else
    ' ... otherwise its between 20 and 99.
    Select Case Val(Left(MyTens, 1))
        Case 2: Result = "Twenty "
        Case 3: Result = "Thirty "
        Case 4: Result = "Forty "
        Case 5: Result = "Fifty "
        Case 6: Result = "Sixty "
        Case 7: Result = "Seventy "
        Case 8: Result = "Eighty "
        Case 9: Result = "Ninety "
        Case Else
    End Select
    ' convert ones place digit.
    Result = Result & ConvertDigit(Right(MyTens, 1))
End If
ConvertTens = Result
End Function
Private Function ConvertDigit(ByVal MyDigit)
Select Case Val(MyDigit)
    Case 1: ConvertDigit = "One"
    Case 2: ConvertDigit = "Two"
    Case 3: ConvertDigit = "Three"
    Case 4: ConvertDigit = "Four"
    Case 5: ConvertDigit = "Five"
    Case 6: ConvertDigit = "Six"
    Case 7: ConvertDigit = "Seven"
    Case 8: ConvertDigit = "Eight"
    Case 9: ConvertDigit = "Nine"
    Case Else: ConvertDigit = ""
End Select
End Function

answered Dec 27, 2019 at 10:34

S FAIZULLAH BASHA's user avatar

Dim XN As Integer
Dim XS As String

XN = 10
XS = Trim(Str(XN))  'now XS = "10"

answered Mar 11, 2020 at 5:56

Matu's user avatar

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

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

Понравилась статья? Поделить с друзьями:
  • Excel vba цвет ячейки диапазон
  • Excel vba цвет ячеек строки
  • Excel vba цвет ярлыка листа
  • Excel vba установить автофильтр
  • Excel vba условные операторы