Word vba число в строку

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

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. Отличительная особенность данных функций vba преобразования типов от остальных – префикс C (от слова Convert), после которого следует краткое имя типа данных, к которому происходит преобразование (например, Bool – Boolean, Cur – Currency, и так далее).

CBool(par) – Преобразование к типу Boolean. Если параметр par будет отличаться от 0, то функция вернет значение true, в противном случае – false.

CByte(par) – Преобразование к типу Byte. Параметр par должен содержать числовое значение или строку, которые являются числом без знака в диапазоне значений от 0 до 255. Условия преобразования:

  • Если значение дробной части меньше 0.5, то она будет отброшена. В случае, если дробная часть больше 0.5 – к целой части добавится единица. Если же дробная часть ровна 0.5, то произойдет округление до ближайшего четного числа.
  • Если переданный параметр является строкой, то он должен содержать только цифры, в противном случае произойдет генерация ошибки.
  • В случае, если параметр содержит отрицательное число или число, которое больше 255, то также произойдет генерация ошибки. (vba преобразование типов)

CCur(par) – Преобразование к типу vba Currency. Передаваемый параметр должен содержать значение в диапазоне от -922 337 203 685 477.5808 до 922 337 203 685 477.5807.

Условия преобразования:

  • Если параметр содержит дробное число, содержащее больше 4 знаков в дробной части, то функция округляет его до четырех десятичных знаков.
  • Если параметр не входит в допустимый диапазон, то произойдет генерация ошибки.

CDate(par) – Преобразует переданный параметр vba в тип дата.

CDbl(par) – Преобразование к типу vba Double. Переданный параметр должен содержать любое числовое значение или строку, которые входят в диапазон от -1.79769313486232E308 до -4.94065645841247E-324 для отрицательных значений, и от 4.94065645841247E-324 до 1.79769313486232E308 для положительных значений.

Условия преобразования:

  • Если значение переданного параметра не попадает в допустимый диапазон, то произойдет ошибка. (vba преобразование типов)
  • Если параметр является строкой, содержащей не только цифры, то произойдет ошибка.

CDec(par) – Преобразование к типу vba Decimal. Параметр должен содержать любое числовое или строковое значение, входящее в диапазон представляющий целое число в диапазоне +/-79 228 162 514 264 337 593 543 950 335 или смешанное с не более чем 28 цифрами в дробной части в диапазоне +/-7.9228162514264337593543950335. Минимальным возможным ненулевым числом является 0.0000000000000000000000000001.

Условия преобразования:

  • Если значение параметра не входит в допустимый диапазон – произойдет генерация сообщения об ошибке.
  • Если передаваемый параметр является строкой и содержит не только цифры, то произойдет генерация ошибки.

CInt(par) – Преобразование к типу vba Integer. Передаваемый параметр должен входить в диапазон чисел от -32768 до 32767.

Условия преобразования:

  • Если значение параметра не входит в допустимый диапазон – произойдет генерация сообщения об ошибке. (vba преобразование типов)
  • Если передаваемый параметр является строкой и содержит не только цифры, то произойдет генерация ошибки.
  • Если передаваемый параметр содержит дробную часть, которая равна 0.5, то произойдет округление до ближайшего четного числа.

CLng(par) – Преобразование к типу vba Long, допустимы диапазон передаваемого параметра числа от -2147483648 до 2147483647.

Условия преобразования:

  • Если значение параметра не входит в допустимый диапазон – произойдет генерация сообщения об ошибке.
  • Если передаваемый параметр является строкой и содержит не только цифры, то произойдет генерация ошибки.
  • Если передаваемый параметр содержит дробную часть, которая равна 0.5, то произойдет округление до ближайшего четного числа.

CSng(par) – Преобразование к типу vba Single. Допустимый диапазон — число от -3.402823E8 до -1.401298E-45 для отрицательных значений и от 1.401298E-45 до 3.402823E8 для положительных значений.

Условия преобразования:

  • Если передаваемый параметр содержит значение, которое меньше минимального допустимого значения, то функция вернет значение 0.
  • Если параметр содержит значение, которое превышает максимально допустимое, то произойдет генерация ошибки. (vba преобразование типов)
  • Если передаваемый параметр является строкой и содержит не только цифры, то произойдет генерация ошибки.
  • Если число знаков дробной части в параметре выходит за пределы допустимого диапазона, то функция усекает ее (дробную часть).

CStr(par) – Преобразует переданный параметр в строковое значение.

Str(par) — Аналогично функции CStr, но перед положительными числами вставляется пробел.

CVar(par) – Преобразует переданы параметр в тип vba Varint.

CVDate(par) – Фактически, функция аналогична CDate, и используется только для совместимости.

Val(par) — Извлекает из переданного параметра только цифры.

TypeName(par) – Функция возвращает имя типа данных vba, для переданного параметра.

Следующие функции преобразования vba возвращают логические значения true или false, и предназначены для проверки переданного параметра на конкретный тип данных.

IsNumeric(par) — Число

IsDate(par) — Дата

IsArray(par) — Массив

IsEmpty(par) – Тип Empty

IsError(par) — Ошибка

IsMissing(par) – Необязательный параметр, переданный в процедуру

IsNull(par) – Пустое значение

IsObject(par) — Объект

Для преобразования числового значения к восьмеричному или шестнадцатеричному виду, применяются следующие функции:

Hex(par) – Шестнадцатеричный вид.

Oct(par) – Восьмеричный вид.

Помимо данных функций преобразования типов vba, для формирования восьмеричного или шестнадцатеричного вида числа, можно использовать следующий формат при записи:

&O – Буква O говорит, что мы хотим прописать восьмеричное значение, которое следует после символа O.

&HA — Буква H говорит, что мы хотим прописать шестнадцатеричное значение, которое следует после символа H.

Так как большая часть приведенных функций используется и в языке VBScript, то примеры с ними можно посмотреть в статьях «Урок 4 по VBScript: преобразование типов данных» и «Урок 10 по VBScript: Функции — математические и для работы с подтипами данных«.

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

Понравилась статья? Поделить с друзьями:
  • Word vba текст в одну строку
  • Word vba текст абзаца
  • Word vba таблица с объединенными ячейками
  • Word vba регулярное выражение
  • Word vba поля field