Vba excel cint что это

Return to VBA Code Examples

In this Article

  • CInt Function
    • VBA CInt Convert Expression to Integer
    • VBA CInt Rounding
    • VBA CInt Converting Strings to Integers
    • VBA CInt Run-Time Error 13 Type Mismatch
    • VBA CInt Run-Time Error 6 Overflow
    • VBA CInt Regional Settings
    • VBA CInt Converting Booleans to Integers
    • VBA CInt Converting Dates to Integers

This tutorial will demonstrate how to use the CInt VBA function to convert an expression to the integer data type.

CInt Function

VBA CInt Convert Expression to Integer

The VBA CInt function can be used to convert expressions to integer data type inside VBA code. The resulting number is rounded to become an integer.

Sub CIntExample_1()
MsgBox CInt(12.34)  'Result is: 12
MsgBox CInt(12.345) 'Result is: 12
MsgBox CInt(-124)   'Result is: -124
MsgBox CInt(-12.34) 'Result is: -12
End Sub

VBA CInt Rounding

The VBA CInt function will round the decimal part of a number type or a number like expression. However, it does not round correctly in all cases. When the decimal part is 0.5 then VBA CInt function returns the closest even integer.

Sub CIntExample_2()
MsgBox CInt(0.34)
'Result is:    0

MsgBox CInt(0.99)
'Result is:    1

MsgBox CInt(-124.95)
'Result is:    -125

MsgBox CInt(1.5)
'Result is:    2

MsgBox CInt(2.5)
'Result is:    2
End Sub

We can add a decimal number relatively small to our expected decimal value to change the behavior of VBA Cint function to the expected.

Sub CIntExample_3()
MsgBox CInt(2.5)
'Result is:    2
MsgBox CInt(2.5 + 0.001)
'Result is:    3

MsgBox CInt(14.5)
'Result is:   14
MsgBox CInt(14.5 + 0.001)
'Result is:   15
End Sub

VBA CInt Converting Strings to Integers

The VBA CInt function can be used to convert strings to integers if the characters in the string have a meaning as numbers.

Sub CIntExample_4()
Dim StrEx As String
StrEx = "112"
MsgBox CInt(StrEx)
'Result is: 112

StrEx = "112.3"
MsgBox CInt(StrEx)
'Result is: 112   --> 112.3 is rounded

StrEx = "11,2"
MsgBox CInt(StrEx)
'Result is: 112   -->  , is ignored

StrEx = "$112"
MsgBox CInt(StrEx)
'Result is: 112   -->  $ is ignored
End Sub

VBA CInt Run-Time Error 13 Type Mismatch

Using VBA Cint function with strings that contain non-numerical characters or characters that don’t have meaning in numerical context will result in a Run-Time error ’13’: Type mismatch.

Sub CIntExample_5()
'The code below will result in an ERROR message
'CInt can’t handle non numerical characters
Dim StrEx As String
StrEx = "Ab13"
MsgBox CInt(StrEx)
End Sub

VBA CInt Run-Time Error 6 Overflow

Using VBA Cint function with strings that result in a value smaller or bigger than the expected integer will result in a Run-Time error ’6’: Overflow. Integer data type in excel has an expected value of -32768 to 32767.

Sub CIntExample_6()
'The code below will result in an ERROR message
'CInt cant handle non numerical characters
Dim StrEx As String
StrEx = "1234567"
MsgBox CInt(StrEx)
End Sub

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

VBA CInt Regional Settings

VBA CInt function has different behavior converting strings with comma or dot.  It uses the Regional Settings of the operating system for decimal separator and digit separator.

Sub CIntExample_7()
Dim StrEx As String
StrEx = "1,9"
MsgBox CInt(StrEx)
‘If Regional settings have , as a grouping separator then 
'Result is: 19
‘If Regional settings have , as a decimal separator then 
'Result is: 2 (2 because 1.9 gets rounded)

StrEx = "1.9"
MsgBox CInt(StrEx)
‘If Regional settings have . as a grouping separator then 
'Result is: 19
‘If Regional settings have . as a decimal separator then 
'Result is: 2 (2 because 1.9 gets rounded)
End Sub

VBA CInt Converting Booleans to Integers

VBA Cint function can convert boolean variables to integers. If the evaluated expression is true the resulting integer is -1 and if the evaluated expression is false, the resulting integer is 0.

Sub CIntExample_8()
Dim BoolEx As Boolean
BoolEx = True
MsgBox CInt(BoolEx)  'Result is: -1
MsgBox CInt(2 = 2)   'Result is: -1

BoolEx = False
MsgBox CInt(BoolEx)  'Result is: 0
MsgBox CInt(1 = 2)   'Result is: 0
End Sub

VBA CInt Converting Dates to Integers

VBA Cint function can convert a date variable to an integer. The returned value is the internal number used by excel for date storage rounded. If that number is outside of the expected integer limits for VBA then we get a  Run-Time error ’6’: Overflow.

Sub CIntExample_9()
Dim DateEx As Date
DateEx = #2/3/1940#
MsgBox CInt(DateEx)
'Result is: 14644
DateEx = #8/7/1964#
MsgBox CInt(DateEx)
'Result is: 23596
End Sub

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

Описание

Microsoft Excel функция CINT преобразует значение в целое число.
Функция CINT — это встроенная в Excel функция, которая относится к категории функций преобразования типов данных. Его можно использовать как функцию VBA в Excel. В качестве функции VBA вы можете использовать эту функцию в коде макроса, который вводится через редактор Microsoft Visual Basic Editor.

Синтаксис

Синтаксис функции CINT в Microsoft Excel:

CInt( expression )

Параметры или аргументы

expression
Значение, которое нужно преобразовать в целое число.

Возвращаемое значение

Функция CINT возвращает целочисленное значение.

Применение

  • Excel для Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 для Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Тип функции

  • Функция VBA

Пример (как функция VBA)

Функцию CINT можно использовать только в коде VBA в Microsoft Excel. Давайте взглянем на некоторые примеры Excel функции CINT, чтобы понять, как использовать функцию CINT в коде Excel VBA:

Dim LValue As Integer

LValue = CInt(8.45)

В этом примере переменная LValue теперь будет содержать значение 8.
Будьте осторожны при использовании CINT.
Если бы вы использовали следующий код:

Dim LValue As Integer

LValue = CInt(8.5)

Переменная LValue по-прежнему будет содержать значение 8.
Пока дробь не будет больше 0.5, функция CINT не будет округлять число в большую сторону.
СОВЕТ:

  • Если дробь меньше или равна 0.5, результат будет округлен в меньшую сторону.
  • Если дробь больше, чем 0.5, результат будет округлен в большую сторону.

Мы сочли полезным в прошлом прибавлять 0.0001 к значение перед применением функции CINT для имитации обычного процесса округления.
Например, CInt (8.50001) приведет к значению 9.

VBA CINT

Excel VBA CInt Function

In this article, we will see an outline on Excel VBA CInt. CInt is a type conversion function. So if we try to understand it in general terms this function is used to convert a value from any other data type to integer data type. The syntax to use this function is actually very simple as it takes just one argument.

Syntax:

VBA CINT Syntax

Though this function is used to convert a value to an integer it is to be noted that the value should be numeric. A non-numeric value will give an error. Actually there are three types of Error that can be encountered while using this function.

How to Use the CInt Function in Excel VBA?

The use of this function is very easy as it takes a single expression as an argument. This function is very useful in certain applications when there is data in multiple forms. This function can be used in a single statement or we can use a user-defined function to call it in another function. We will learn how to use the CInt function in Excel by using the VBA Code.

You can download this VBA CInt Excel Template here – VBA CInt Excel Template

Example #1

Let us begin with the most basic example to show how this function works. As we know CInt function converts any given expression to an integer. So we will provide a basic input and see the result. For this, follow the below steps:

Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.

Insert Module

Step 2: When the module is inserted we can start with our subprocedure for example 1.

Code:

Sub Example1()

End Sub

VBA CInt Example 1-1

Step 3: We will simply provide a decimal value to the function and display it using the Msgbox function.

Code:

Sub Example1()

End Sub

Decimal Value Example1-2

Step 4: Run the code by pressing the F5 key or by clicking on the Play Button.

VBA CInt Example 1-3

We can see that we have given the input a decimal value but the function converted the value to an integer.

Example #2

Let us have some value in any sheet and try to convert it to an integer using the function. The value what I have in sheet 1 for cell A1 is as follows. For this, follow the below steps:

VBA CInt Example 2-1

Step 1: Declare another subprocedure for example 2 for this circumstance.

Code:

Sub Example2()

End Sub

VBA CInt Example 2-2

Step 2: Now declare two variables one as String and another one as Integer.

Code:

Sub Example2()

Dim A As String, B As Integer

End Sub

Integer Example 2-3

Step 3: Assign the value of cell A1 to variable A.

Code:

Sub Example2()

Dim A As String, B As Integer
A = Range("A1").Value

End Sub

VBA CINT Example 2-4

Step 4: And then in the variable B we will convert the value of A to Integer using the CInt function.

Code:

Sub Example2()

Dim A As String, B As Integer
A = Range("A1").Value
B = CInt(A)

End Sub

VBA CInt Example 2-5

Step 5: To see our result if the value is displayed or not let us use the Msgbox function as variable A is a string data type.

Code:

Sub Example2()

Dim A As String, B As Integer
A = Range("A1").Value
B = CInt(A)
MsgBox B

End Sub

String Data Type. Example 2-6

Step 6: Run the code by pressing the F5 key or by clicking on the Play Button.

VBA CInt Example 2-7

Example #3

The practical example of this function will be very good when we take any input from the user. So now for this example let the user give any values and we will display it by converting the value to an integer using the CInt function. For this, follow the below steps:

Step 1: Declare another sub procedure to start with this example.

Code:

Sub Example3()

End Sub

VBA CInt Example 3-1

Step 2: Now we will declare two variables, one as Integer and one as any other data type but for this example, I have taken it as a long data type.

Code:

Sub Example3()

Dim A As Long, B As Integer

End Sub

VBA CInt Example 3-2

Step 3: In the variable A store the input we will get from the user using the input box function.

Code:

Sub Example3()

Dim A As Long, B As Integer
A = InputBox("Enter a Decimal Value")

End Sub

VBA CInt Example 3-3

Step 4: Now in the variable B store the input received from the user and convert it to an integer using the CInt function.

Code:

Sub Example3()

Dim A As Long, B As Integer
A = InputBox("Enter a Decimal Value")
B = CInt(A)

End Sub

VBA CInt Example 3-4

Step 5: Now we can go ahead and display the value which we have converted to the user as follows.

Code:

Sub Example3()

Dim A As Long, B As Integer
A = InputBox("Enter a Decimal Value")
B = CInt(A)
MsgBox "The Number you entered is " & A

End Sub

VBA CInt Example 3-5

Step 6: Now when we execute the code above first we will get a pop up to enter a decimal value.

VBA CInt Example 3-6

Step 7: When we press Ok we can see the result is converted to an integer.

VBA CInt Example 3-7

Example #4

Now as in example 3 we asked a user to provide any value and we tried to convert it to an integer. But multiple users can insert different types of values so what if someone puts value which is not in range for integer we will get an error. For this, follow the below steps:

Step 1: We can again execute the code of example 3 and put the values.

VBA CInt Example 4-1

Step 2: Now we can click on OK.

Run Time Error Example 4-2

We receive a run time error because the storage capacity of an integer value is overflown and variable B cannot store this value.

Step 3: So in this example, we will put an error handler for the CInt function, so for example 4 let us use the same code of example 3 as shown below.

Code:

Sub Example4()

Dim A As Long, B As Integer
A = InputBox("Enter a Decimal Value")
B = CInt(A)
MsgBox "The Number you entered is " & A

End Sub

Error Handler Example 4-3

Step 4: But we will make a few changes before we begin to process the input let us use the error handler on error Go to.

Code:

Sub Example4()

Dim A As Long, B As Integer
On Error GoTo 100:
A = InputBox("Enter a Decimal Value")
B = CInt(A)
MsgBox "The Number you entered is " & A
100:
MsgBox "The value cannot be Converted"
End

End Sub

VBA CInt Example 4-4

Step 5: Now when we run the code by pressing the F5 key. It provides the same input.

VBA CINT Example 4-5

Step 6: Let us see what happens when we press Ok.

Type of Error Example 4-6

This is one of the type of error we have handled for CInt function.

Conclusion

So we saw what CInt function can do and we have said earlier that there can be three types of errors associated with this function. So let us discuss those three types.

In the first case, we saw that if a user or any value is provided to the variable which is out of the range for the integer. The second instance can be if the value is non-numeric. The third and last type of error we can encounter using this function is for an array.

Things to Remember

The important things to remember about these functions are:

  • Non Numeric Values will not be converted and it will show as an error.
  • CInt function cannot be used in an array.
  • If the values exceed the range of integer we will encounter an error.
  • If the values are in decimal places this function rounds the values with the respective decimals.

Recommended Articles

This is a guide to VBA CInt. Here we discuss how to Use the CInt Function in Excel VBA along with practical examples and downloadable excel template. You can also go through our other related articles to learn more –

  1. VBA SendKeys
  2. VBA Name Worksheet
  3. VBA On Error Goto
  4. VBA Msgbox Yes/No

totn Excel Functions


This Excel tutorial explains how to use the Excel CINT function with syntax and examples.

Description

The Microsoft Excel CINT function converts a value to an integer.

The CINT function is a built-in function in Excel that is categorized as a Data Type Conversion Function. It can be used as a VBA function (VBA) in Excel. As a VBA function, you can use this function in macro code that is entered through the Microsoft Visual Basic Editor.

Syntax

The syntax for the CINT function in Microsoft Excel is:

CInt( expression )

Parameters or Arguments

expression
The value to convert to an integer.

Returns

The CINT function returns an integer value.

Applies To

  • Excel for Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Type of Function

  • VBA function (VBA)

Example (as VBA Function)

The CINT function can only be used in VBA code in Microsoft Excel.

Let’s look at some Excel CINT function examples and explore how to use the CINT function in Excel VBA code:

Dim LValue As Integer

LValue = CInt(8.45)

In this example, the variable called LValue would now contain the value of 8.

Be careful using CINT. If you were to use the following code:

Dim LValue As Integer

LValue = CInt(8.5)

The variable LValue would still contain the value of 8. Until the fraction is greater than .5, the CINT function will not round the number up.

TIP:

  • If the fraction is less than or equal to .5, the result will round down.
  • If the fraction is greater than .5, the result will round up.

We’ve found it useful in the past to add 0.0001 to the value before applying the CINT function to simulate the regular rounding process.

For example, CInt(8.50001) will result in a value of 9.

VBA CInt Function in Excel is categorized as a Data Type Conversion function. It is a built-in function in Excel VBA. This VBA CInt function converts an expression to an Integer data type.

This function use in either procedure or function in a VBA editor window in Excel. We can use this VBA CInt Function in 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 CInt function, where we can use this VBA CInt Function and it’s real-time examples.

Table of Contents:

  • Overview
  • Syntax of VBA CInt Function
  • Parameters or Arguments
  • Where we can apply or use VBA CInt Function?
  • Example 1: Convert a String(100) to Integer Data Type
  • Example 2: Convert a Value(12345.678) to Integer Data Type
  • Example 3: Convert a Value(40000) to Integer Data Type (Returns an Overflow Error)
  • Example 4: Convert a string(Test) to Integer Data Type (Returns an Type mismatch Error)
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

The syntax of the CInt Function in VBA is

CInt(Expression)

The CInt function returns a integer data type value.

Parameters or Arguments:

The CInt function has one argument in Excel VBA.
where
Expression:It is a mandatory argument. An expression argument represents a numeric or string value. It is used to convert the value to a integer value.

Where we can apply or use VBA CInt Function?

We can use this CInt 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 Integer Data Type

Here is a simple example of the VBA CInt function. This below example specifies expression(100) converts to an integer type value.

'Convert a String(100) to Integer Data Type
Sub VBA_CInt_Function_Ex1()

    'Variable declaration
    Dim sValue As String
    Dim dResult As Double
    
    sValue = 100
        
    dResult = CInt(sValue)
        
    MsgBox "String(100) to Integer Data Type : " & dResult, vbInformation, "VBA CInt Function"
    
End Sub

Output: Here is the screen shot of the first example output.
VBA CInt Function

Example 2: Convert a Value(12345.678) to Integer Data Type

Here is a simple example of the VBA CInt function. This below example specifies expression(12345.678) converts to an integer type value.

'Convert a Value(12345.678) to Integer Data Type
Sub VBA_CInt_Function_Ex2()

    'Variable declaration
    Dim sValue As Double
    Dim dResult As Double
    
    sValue = 12345.678
        
    dResult = CInt(sValue)
        
    MsgBox "Value(12345.678) to Integer Data Type : " & dResult, vbInformation, "VBA CInt Function"
    
End Sub

Output: Here is the screen shot of the second example output.
VBA CInt Function

Example 3: Convert a Value(40000) to Integer Data Type (Returns an Overflow Error)

Here is a simple example of the VBA CInt function. This below example specifies expression(40000) converts to an intger type value. It returns an Overflow error. The value 40,000 is greater than 32,767. The integer value should be in between -32,768 to 32,767.

'Convert a Value(40000) to Integer Data Type (Returns an Overflow Error)
Sub VBA_CInt_Function_Ex3()

    'Variable declaration
    Dim sValue As Currency
    Dim dResult As Double
    
    sValue = 40000
        
    dResult = CInt(sValue)
        
    MsgBox "Value(40000) to Integer Data Type : " & dResult, vbInformation, "VBA CInt Function"
End Sub

Output: Here is the screen shot of the third example output.
VBA Runtime Overflow Error

Example 4: Convert a string(Test) to Integer Data Type (Returns an Type mismatch Error)

Here is a simple example of the VBA CInt function. This below example specified expression(Test) converts to an integer type value. It returns Type mismatch error.

'Convert a string(Test) to Integer Data Type (Returns Type mismatch Error)
Sub VBA_CInt_Function_Ex4()

    'Variable declaration
    Dim sValue As String
    Dim dResult As Double
    
    sValue = "Test"
        
    dResult = CInt(sValue)
        
    MsgBox "String(Test) to Integer Data Type : " & dResult, vbInformation, "VBA CInt Function"
    
End Sub

Output: Here is the screen shot of the fourth example output.
VBA Runtime Overflow Error

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

Home / VBA / Top VBA Functions / VBA CINT Function (Syntax + Example)

The VBA CINT function is listed under the data type conversion category of VBA functions. When you use it in a VBA code, it converts an expression into an integer. In simple words, an integer as per VBA’s integer data type can be any value between -32,768 and 32,767 (without any decimals).

CInt(Expression)

Arguments

  • Expression: The value which you want to convert to an integer.

Example

To practically understand how to use the VBA CINT function, you need to go through the below example where we have written a vba code by using it:

Sub example_CINT()
Range("B1").Value = CInt(Range("A1"))
End Sub

In the above example, we used the value from cell A1 (9.76) and then we used the CINT function to convert that value into an integer data type and it returned 10 in the result.

Notes

  • CINT will round that number that is greater than 0.5 and round down if lower than or equals 0.5.
  • If you supply a number that is out of the range of integer data type (-32,768 and 32,767), VBA will return the run-time 13 error.

Понравилась статья? Поделить с друзьями:
  • Vba excel checkbox на листе
  • Vba excel checkbox в ячейке
  • Vba excel checkbox click
  • Vba excel check if sheet exist
  • Vba excel cells формат