Vba excel функции целое

Access для Microsoft 365 Access 2021 Access 2019 Access 2016 Access 2013 Access 2010 Access 2007 Еще…Меньше

Возвращает целую часть числа.

Синтаксис

Int
(

число

)

Fix(

число

)

Обязательный аргумент числоаргумент представляет собой значение типа Double или любое допустимое числовое выражение. Если число содержит значение NULL, возвращается NULL.

Замечания

Функции Int и Fix удаляют дробную часть числа и возвращают полученное целое значение.

Различие между функциями Int и Fix состоит в том, что при отрицательном значении числа функция Int возвращает первое отрицательное целое число, не превышающее число, а функция Fix — первое отрицательное целое число, которое больше числа или равно ему. Например, функция Int преобразует -8,4 в -9, а Fix преобразует -8,4 в -8.

Функция Fix(число) вычисляется следующим образом:

Sgn(number) * Int(Abs(number))


Примеры запросов


Выражение


Результаты:

SELECT Int([Discount]) AS Expr1 FROM ProductSales;

Удаляет дробную часть всех значений в поле «Скидка» и возвращает итоги для всех значений. Для отрицательных дробей «Int» возвращает первое отрицательное integer, меньшее или равное числу. Например, для значения скидки «-223,20» возвращается значение -224,00.

SELECT Fix([Discount]) AS Expr1 FROM ProductSales;

Удаляет дробную часть всех значений в поле «Скидка» и возвращает итоги для всех значений. Для отрицательных дробей «Исправить» возвращает первое отрицательное integer, большее или равное числу. Например, для значения скидки «-223,20» возвращается значение -223,00.

Пример VBA

Примечание: В примерах ниже показано, как использовать эту функцию в модуле Visual Basic для приложений (VBA). Чтобы получить дополнительные сведения о работе с VBA, выберите Справочник разработчика в раскрывающемся списке рядом с полем Поиск и введите одно или несколько слов в поле поиска.

В данном примере показано, как функции Int и Fix возвращают целые части чисел. Если значением аргумента является отрицательное число, функция Int возвращает первое отрицательное целое число, не превышающее его, а функция Fix — первое отрицательное целое число, которое больше этого значения или равно ему.

Dim MyNumber
MyNumber = Int(99.8) ' Returns 99.
MyNumber = Fix(99.2) ' Returns 99.
MyNumber = Int(-99.8) ' Returns -100.
MyNumber = Fix(-99.8) ' Returns -99.
MyNumber = Int(-99.2) ' Returns -100.
MyNumber = Fix(-99.2) ' Returns -99.

Нужна дополнительная помощь?

Возвращение целой части дробного десятичного числа с помощью функций Int и Fix в VBA Excel. Синтаксис, правила округления, примеры.

Int – это функция, которая удаляет дробную часть исходного числа и возвращает целое число меньшее или равное исходному числу.

Синтаксис:

Функция Fix

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

Другими словами, функция Fix просто отбрасывает дробную часть исходного числа, возвращая целую часть без каких-либо преобразований (смотрите примеры).

Синтаксис:

Примеры

Сходство и различие функций Int и Fix на примерах:

MsgBox Int(9.1) ‘Результат: 9

MsgBox Fix(9.1) ‘Результат: 9

MsgBox Int(9.9) ‘Результат: 9

MsgBox Fix(9.9) ‘Результат: 9

MsgBox Int(9.1) ‘Результат: -10

MsgBox Fix(9.1) ‘Результат: -9

MsgBox Int(9.9) ‘Результат: -10

MsgBox Fix(9.9) ‘Результат: -9


Главная » Функции VBA »

28 Апрель 2011              129137 просмотров

  • ABS() — эта функция возвращает абсолютное значение переданного ей числа (то же число, но без знака). Например, ABS(3) и ABS(-3) вернут одно и то же значение 3.
  • Int(), Fix() и Round()позволяют по разному округлять числа:
    • Int() возвращает ближайшее меньшее целое;
    • Fix() отбрасывает дробную часть;
    • Round() округляет до указанного количества знаков после запятой.

    Однако Round может вернуть не совсем ожидаемый результат, т.к. функция применяет финансовое округление. По правилам данного округления если за последней к округлению цифрой стоит 5, то округляемую цифру увеличивают в том случае, если она нечетная и уменьшают, если четная.
    Математическое же округление всегда округляет цифру в большую сторону, если за ней идет цифра 5 и выше, и отбрасывает остаток если 4 и меньше.
    Т.е. если мы выполним такую строку кода

    то результатом будет 2,5, хотя предполагалось получить 2,51. Поэтому порой для округления лучше использовать Format:

        MsgBox Format(2.505, "#,##0.00")

    но в этом случае мы получим не число в чистом виде, а текст. И если нужно именно число, то придется производить дополнительные преобразования:

        MsgBox CDbl(Format(2.505, "#,##0.00"))

    Так же, для математического округления, можно использовать и такой вариант:

        MsgBox Application.Round(2.505, 2)

    Но здесь стоит учитывать, что это не чистый VB и этот метод сработает только в Excel, т.к. по сути мы обращаемся к встроенной в Excel функции округления ОКРУГЛ(ROUND), которая применяет именно математическое округление.

  • Rnd и команда Randomize используются для получения случайных значений (очень удобно для генерации имен файлов и в других ситуациях). Перед вызовом функции Rnd() необходимо выполнить команду Randomize для инициализации генератора случайных чисел.
        Dim lRundNum As Long, lMinNum As Long, lMaxNum As Long
        lMinNum = 1: lMaxNum = 100
        Randomize
        lRundNum = Int(lMinNum + (Rnd() * lMaxNum))
        MsgBox lRundNum
  • Sgn() — позволяет вернуть информацию о знаке числа. Возвращает 1, если число положительное, -1, если отрицательное и 0, если проверяемое число равно 0.
  • Mod() — Делит два числа и возвращает только остаток. Например, выражение 8 Mod 3 вернет число 2, т.к. без остатка(в виде дроби у результата деления) 8 делится на 3 только до 2-х(8 / 3 = 2,66666666666667).
    При этом функция Mod учитывает и знак числа — если первое число или оба числа отрицательные, то результатом будет отрицательное число. Если же отрицательное только второе число — то результат будет положительным числом.
    При попытке получить остаток при делении чисел с плавающей запятой результат может быть не тем, который ожидается, потому что перед выполнением деления оба числа округляются по математическим законам(5 и выше до большего, 4 и ниже — до меньшего). Например, выражение 8 Mod 3.5 вернет 0, а выражение 8 Mod 3.4 — 2.

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

The VBA INT function is listed under the math category of VBA functions. When you use it in a VBA code, it can round down a number to an integer. In simple words, it rounds a positive number toward zero and a negative number away from zero. It simply works like the INT function in the worksheet.

Int(Number)

Arguments

  • Number: The numeric value from which you want the integer part.

Example

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

Sub example_INT()
Range("B1").Value = Int(Range("A1"))
End Sub

In the above code, we have used INT to get the integer part from the value (13.54) that we have in cell A1 and return the result in cell B1. And when we run the code it returned the 13 in cell B1.

Notes

  • If the value specified is a value other than a number or a string that can’t be recognized as a number, VBA will return the run-time 13 error.
  • If the supplied number is positive then it rounds that number toward zero and if the supplied number is negative then away from zero.

Excel VBA INT (Integer) Function

VBA INT is an inbuilt function that only gives us the integer part of a number that provides input. One may use this function in those data whose decimal part is not so much affecting the data. So to ease the calculations or analysis, we use the INT function to get only the integer values.

This function is available with the worksheet as well as in VBA. The Integer function rounds a specific number down to the nearest integer number.

VBA INT

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 INT (wallstreetmojo.com)

One can use the VBA Int function in the Sub and Function procedures. Now, look at the syntax of the INT function in VBA.

VBA INT Formula

It has only one argument to supply, Number.

  • The number
  • is the number we are trying to convert to an INTEGER number. When we supply the number, the INT function rounds it down to the nearest Integer.

For example, if the supplied number is 68.54, the Excel VBA INT function rounds down to 68 toward zero. On the other hand, if the supplied number is -68.54, then the INT function rounded the number to 69, away from zero.

Table of contents
  • Excel VBA INT (Integer) Function
    • How to use VBA INT Function?
      • Example #1
      • Example #2
      • Example #3 – Extract Date Portion from Date & Time
    • Recommended Articles

How to use VBA INT Function?

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

Example #1

Look at the simple example of the INT function in VBA. Let us perform the task of rounding the number 84.55 to the nearest integer number.

Step 1: Start the subprocedure.

Step 2: Declare the variable as Integer.

Code:

Sub INT_Example1()

  Dim K As Integer

End Sub

excel vba integer Example 1

Step 3: Now, assign the formula to the variable “k” by applying the INT function.

Code:

Sub INT_Example1()

  Dim K As Integer

  K = Int(

End Sub

excel vba integer Example 1-1

Step 4: Supply the number as 84.55.

Note: Since it is a numerical number, we need not supply double quotes.

Code:

Sub INT_Example1()

  Dim K As Integer

  K = Int(84.55)

End Sub

VBA INT Example 1-2

Step 5: Now pass the variable in the VBA message boxVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.

Code:

Sub INT_Example1()

  Dim K As Integer

  K = Int(84.55)
  MsgBox K

End Sub

excel vba integer Example 1-3

Let us run the code and see what happens.

excel vba integer Example 1-4

So, the result is 84 and rounded down to the nearest integer value.

Example #2

Now with the same number with the negative sign, we will try to convert to the nearest integer value. Below is the code with a negative sign.

Code:

Sub INT_Example2()

  Dim k As Integer

  k = Int(-84.55)
    'Negative number with INT function
  MsgBox k

End Sub

When we run this code, it has rounded the number to -85.

VBA INT Example 2

A few times in our careers, we have encountered the scenario of extracting the date and time separately from the combination of Date and Time.

For example, look at the below data of Date and Time.

Extract Date & Time Example 3

How do you extract the Date and Time portion?

First, we need to extract the Date portion. For this, let us apply the INT function. The below code will extract the DATE portion from the above data.

Code:

Sub INT_Example2()

  Dim k As Integer

  For k = 2 To 12
    Cells(k, 2).Value = Int(Cells(k, 1).Value)
    'This will extract date to the second column

    Cells(k, 3).Value = Cells(k, 1).Value - Cells(k, 2).Value
    'This will extract time to the third column
  Next k

End Sub

Run this code. You might get the result like the below (if the formatting is not applied).

Extract Date & Time Example 3-1

In the date column, apply the formatting as DD-MMM-YYYY,” and for the time column, apply the date format in excelThe date format in Excel can be changed either from the “number format” of the Home tab or the “format cells” option of the context menu.read more as HH:MM: SS AM/PM.”

Date & Time column

Recommended Articles

This article has been a guide to VBA INT Function. Here, we learn how to use the VBA INT function, practical examples, and a downloadable Excel template. Below are some useful Excel articles related to VBA: –

  • Find and Replace Function in VBA
  • VBA CDBL Function
  • Copy Paste in VBA
  • 1004 Error in VBA
  • VBA Variable Types

totn Excel Functions


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

Description

The Microsoft Excel INT function returns the integer portion of a number.

The INT function is a built-in function in Excel that is categorized as a Math/Trig Function. It can be used as a worksheet function (WS) and a VBA function (VBA) in Excel. As a worksheet function, the INT function can be entered as part of a formula in a cell of a worksheet. 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 INT function in Microsoft Excel is:

INT( expression )

Parameters or Arguments

expression
A numeric expression whose integer portion is returned.

Note

  • If the expression is negative, the INT function will return the first negative number that is less than or equal to the expression.

Returns

The INT 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

  • Worksheet function (WS)
  • VBA function (VBA)

Example (as Worksheet Function)

Let’s look at some Excel INT function examples and explore how to use the INT function as a worksheet function in Microsoft Excel:

Microsoft Excel

Based on the Excel spreadsheet above, the following INT examples would return:

=INT(A1)
Result: 210

=INT(A2)
Result: 2

=INT(A3)
Result: -3

=INT(-4.5)
Result: -5

Example (as VBA Function)

The INT function can also be used in VBA code in Microsoft Excel.

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

Dim LNumber As Double

LNumber = Int(210.67)

In this example, the variable called LNumber would now contain the value of 210.

VBA INT

VBA INT

There are different data types used with Excel VBA. According to the data we use different among them. An integer is a number which is not a fraction that can be negative, positive and zero. INT is referred as integer function. This is used to change the data into an integer in excel. This can be used as an excel function as well as VBA function.

INT function is grouped under ‘Math & Trigonometry’ functions. Integer function is used to round the particular number down to its nearest integer number. If the number is negative, then the integer will round the number away with respect to zero.

How to Use INT Function in Excel VBA?

Similar to the excel function Integer function is used by supplying a single argument.

Below is the syntax of Excel VBA INT:

Syntax of INT

  • The number supplied should be a number(Double) or a cell reference.
  • When the same is expressed in VBA code.

A variable is defined as an integer and the function is applied to the variable

Dim n As Integer
n = Int (34.98)

Now the supplied number will be changed into and rounded to a number down near to the given integer.

Examples of Excel VBA INT Function

Below are a few practical examples of the VBA INT Function in Excel.

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

Excel VBA INT – Example #1

How does the INT function work with positive numbers?

If the given number is a positive double number or fraction number, let’s see how it will be work while used with INT function.

Follow the below steps to use Excel VBA INT Function:

Step 1: Open the code window. To start the operation create a private function ‘integerconversion’ where the entire code will be return.

Code:

Private Sub integerconversion()

End Sub

VBA INT Example 1-1

Step 2: Since the result will be an integer we need a variable as integer to assign the result of INT function. Declare a variable within the function ‘n’ as an integer to assign the INT function to this variable.

Code:

Private Sub integerconversion()

Dim n As Integer

End Sub

VBA INT Example 1-2

Step 3: Once the variable is created assign the integer function formula to the created variable ‘n’. Now while operating the function the result will be stored into the integer variable.

Code:

Private Sub integerconversion()

Dim n As Integer
n = Int(

End Sub

VBA INT Example 1-3

Step 4: A positive fraction number is supplied to the INT function to see how it will be rounded to its nearest integer. ’34.98’ is the number used and it is given to the INt function as an argument.

Code:

Private Sub integerconversion()

Dim n As Integer
n = Int(34.98)

End Sub

VBA INT Example 1-4

Step 5: Now the INT function is operated and the result will be stored within the declared variable ‘n’. To see the result pass the variable into a message box, which will print the variable value in a message box.

Code:

Private Sub integerconversion()

Dim n As Integer
n = Int(34.98)
MsgBox n

End Sub

VBA INT Example 1-5

Step 6: The code is completed now press F5 or run the code using the run button within the code window to get the final result. It will show the output in a message box.

Result of Example 1-6

Check the message inside the message box. The result is rounded to an integer 34 from 34.98 to the integer down near to 34.98

Excel VBA INT – Example #2

How does the INT function work with negative numbers?

Within the same code lets try to use a negative number. If the same number is supplied as negative, let’s see how the result will change

Follow the below steps to use Excel VBA INT Function:

Step 1: Here the same code will be changed as below where the number is supplied as negative fraction number within the INT function. ‘-34.98’ is used with the INt function.

Code:

Private Sub integerconversion()

Dim n As Integer
n = Int(-34.98)

End Sub

VBA INT Example 2-1

Step 2: Use the message box to print the result to the window.

Code:

Private Sub integerconversion()

Dim n As Integer
n = Int(-34.98)
MsgBox n

End Sub

VBA INT Example 2-2

Step 3: Run the code below and the result will be changed.

Result of Example 2-3

The result will be a negative integer. And is rounded to the near integer away from zero.

Here the number -34.98 is rounded to -35 while applying the INT function on it. The INT function will always round the number down to the next lowest integer.

Excel VBA INT – Example #3

How to Separate date and time from a single cell using VBA INT?

Few dates are mentioned with time in the same cell we want to separate the data into different cells.

The first column contains few dates with time. Here we want to split the data into two different columns.

Example 3-1

To separate the data into the different columns date, time let’s use the INT function. Create a button which can produce the expected result in a single click.

VBA INT Example 3-2

Now let’s write the VBA code behind this command button. For this, Follow the below steps to use Excel VBA INT Function:

Step 1: Double click on the command button and code window will appear as below.

Code:

Private Sub CommandButton1_Click()

End Sub

VBA INT Example 3-3

Step 2: Create a variable as an integer to run a For loop to separate the data one by one.

Code:

Private Sub CommandButton1_Click()

Dim i As Integer

End Sub

VBA INT Example 3-4

Step 3: Implement a For loop, since we have 5 rows the loop should work 5 times. Where the row starts from 2.

Code:

Private Sub CommandButton1_Click()

Dim i As Integer
For i = 2 To 6

End Sub

VBA INT Example 3-5

Step 4: Using INT function split the date into the 2nd Where the date only will be split into the 2nd column.

Code:

Private Sub CommandButton1_Click()

Dim i As Integer
For i = 2 To 6
  Cells(i, 2).Value = Int(Cells(i, 1).Value)

End Sub

VBA INT Example 3-6

Step 5: By subtracting the INT function result from the first column get the remaining data into a 3rd cell.

Code:

Private Sub CommandButton1_Click()

Dim i As Integer
For i = 2 To 6
  Cells(i, 2).Value = Int(Cells(i, 1).Value)
  Cells(i, 3).Value = Cells(i, 1).Value - Cells(i, 2).Value
Next

End Sub

VBA INT Example 3-7

Step 6: To get the results in a proper format make the cells formatted as below. The column date and time set into the format which you want. Otherwise, the result will be shown as some random numbers or some garbage value.

Date Format:

Date Format

Time Format:

Time Format

Step 7: Run the code by clicking the command button. The output will be as below.

Result of Example 3-10

The data given in the first column will be split into two columns date and time.

Things to Remember

  • If a number is positive, then the integer function will round it to the integer near to zero, for negative values it will down the number to an integer away from zero.
  • VBA INT function will round down the number to an integer value.
  • Keep the cells in the format to get a proper result while using the INT function in Excel VBA.

Recommended Articles

This has been a guide to VBA INT Function. Here we discussed how to use Excel VBA INT Function along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Long
  2. VBA Sort
  3. VBA Get Cell Value
  4. VBA CDEC

Функция Int

Int(Number)

Функция Int(Integer) отбрасывает дробную часть числа и возвращает целое значение. Функция схожа с функцией Fix. Различие между функциями Int и Fix состоит в том, что для отрицательного значения аргумента число функция Int возвращает ближайшее отрицательное целое число, меньшее либо равное указанному, а Fix ближайшее отрицательное целое число, большее либо равное указанному. Например, функция Int преобразует -8.4 в -9, а функция Fix преобразует -8,4 в -8

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

Функция возвращает значение типа, совпадающего с типом аргумента, которое содержит целую часть числа

Параметры

Number Обязательный аргумент Number может представлять любое допустимое числовое выражение или число типа Double. Если аргумент имеет значение Null, то возвращается также Null

Примечание
Если значение аргумента не попадает в диапазон допустимых значений Double, то генерируется ошибка стадии выполнения Overflow
Если аргумент имеет тип данных String, то он должен представлять собой число, иначе генерируется ошибка стадии выполнения Type mismatch

Пример

' В данном примере 
' функции Int и Fix возвращают целые части чисел.
' В случае отрицательного аргумента Int возвращает
' ближайшее отрицательное целое число,
' меньшее либо равное указанному,
' а Fix ближайшее отрицательное целое число,
' большее либо равное указанному

Dim MyNumber
MyNumber = Int(99.8) ' Возвращает 99
MyNumber = Fix(99.2) ' Возвращает 99

MyNumber = Int(-99.8) ' Возвращает -100
MyNumber = Fix(-99.8) ' Возвращает -99

MyNumber = Int(-99.2) ' Возвращает -100
MyNumber = Fix(-99.2) ' Возвращает -99

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