Перевод числа в строку vba excel

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

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 Convert Number To String, we use CStr data type conversion VBA function. The number can be integer, or any numeric value. In the following article let us see an example. And also see the step by step instructions to run VBA code in the visual basic editor(VBE) window. You can find link at the end of the session to know more about CStr VBA function.

Convert Number to String

Let us see an example VBA macro code how to convert number to string.

'VBA Convert Number to Function
Sub VBAF1_Convert_Number_to_Function()

    'Variable Declaration
    Dim iNum As Integer, sResult As String
    
    'Assign value to variable
    iNum = 100
    
    'Check given input value is number or not
    If IsNumeric(iNum) Then
        sResult = CStr(iNum)
        MsgBox sResult, vbInformation, "VBAF1"
    Else
        MsgBox "Enter valid number.", vbInformation, "VBAF1"
    End If

End Sub

Explanation: First we are checking given input value is numeric or not.To check we are using IsNumeric VBA function. This function is a VBA information function. Once we are done with checking, if it is numeric value then converting number to a string value. Run this code in debug mode. Stop at msgbox as shown in the following screen shot. Put cursor on iNum and then notice given input value has converted to string. It is in double quotes.

VBA Convert Number To String

VBA Convert Number To String

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 VBA Text Files VBA Tables

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog

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
  • Перевод числа в hex excel
  • Перевод чисел в текст прописью excel
  • Перевод формата времени в число в excel
  • Перевод формата rtf в word