Что такое abs excel vba

Home / VBA / Top VBA Functions / VBA ABS Function (Get Absolute Value)

The VBA ABS function is listed under the math category of VBA functions. When you use it in a VBA code, it returns an absolute number in the result. In simple words, it returns a non-negative number which means if you specify a negative number it will remove its sign and returns it in the result.

Syntax

Abs(Number)

Arguments

  • Number: The number which you want to convert into an absolute value (number).

Example

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

Sub example_ABS()
Range("B1").Value = Abs(Range("A1"))
End Sub

In the above example, we have used the value from cell A1 where we have a negative number (-1029) and then we have used the ABS function to convert that value into an absolute number and enter that value in cell B1. So basically when you run this code it simply takes the value from cell A1 and converts it into an absolute number.

Notes

  • If the value specified is a value other than a number or a number that can’t be recognized as a number, VBA will return the run-time 13 error.
  • If the value supplied is NULL then it will return a NULL in the result.

Return to VBA Code Examples

Abs Description

Returns the absolute value of a number.

Simple Abs Examples

Sub Abs_Example()
    MsgBox Abs(-12.5)
End Sub

This code will return 12.5

Abs Syntax

In the VBA Editor, you can type  “Abs(” to see the syntax for the Abs Function:

The Abs function contains an argument:

Number: A numeric value.

Examples of Excel VBA Abs Function

you can reference a cell containing a date:

Sub Abs_Example1()
    Dim cell As Range
    
    For Each cell In Range("A2:A4")
        cell.Offset(0, 1) = Abs(cell.Value)
    Next cell
End Sub

The result will be as following.(please see B2:B4)

The following 2 examples both will return 12.

MsgBox Abs(-12)
MsgBox Abs(12)

To find a number closest to 2 when a number array (1.5, 3.1, 2.1, 2.2, 1.8) is given, you can use the following code.

Sub Abs_Example2()
    Dim Numbers
    Dim item
    Dim closestValue As Double
    Dim diff As Double
    Dim minDiff As Double
    minDiff = 100
    
    Numbers = Array(1.5, 3.1, 2.1, 2.2, 1.8)
        
    For Each item In Numbers
        diff = Abs(item - 2)
        If diff < minDiff Then
            minDiff = diff
            closestValue = item
        End If
    Next item

    MsgBox "The closest value: " & closestValue
End Sub

The result will be 2.1 as following.

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!

VBA Abs function in Excel is categorized as Math(Mathematical) & Trig function. This is a built-in Excel VBA Function. This function returns or calculates an absolute value of a number. This function removes negative sign in front of number. The Abs function converts negative value to positive value.

We can use this function in Excel and VBA. This function can be used in either procedure or function in a VBA editor window in Excel. We can use this VBA Abs Function in any number of times in any number of procedures or functions. Let us learn what is the syntax and parameters of the Abs function, where we can use this Abs Function and real-time examples in Excel VBA.

Table of Contents:

  • Objective
  • Syntax of VBA Abs Function
  • Parameters or Arguments
  • Where we can apply or use VBA Abs Function?
  • Example 1: Convert a value(-4) to an absolute number
  • Example 2: Convert a value(4) to an absolute number
  • Example 3: Convert a value(0) to an absolute number
  • Example 4: Convert a value(“Text”) to an absolute number
  • Example 5: Convert a value(Null) to an absolute number
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

The syntax of the Abs Function in VBA is

Abs(Number)

The Abs function returns a numeric value.

Parameters or Arguments:

The Abs function has one argument in Excel VBA.
where
Number:The Number is a required parameter. It represents a number or numeric value. We use this parameter to calculate absolute value.
Note:

  • The specified value is not a number, it returns an error (Run time: Type mismatch error)
  • The specified number has negative sign, it removes negative sign and returns positive value.
  • The specified number is Null, then it returns Null.
  • The specified number is zero(0), then it returns zero(0).

Where we can apply or use VBA Abs Function?

We can use this Abs 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 value(-4) to an absolute number

Here is a simple example of the VBA Abs function. This below example converts a value(-4) to an absolute number. The below example removes negative sign and returns an output as 4.

'Convert a value(-4) to an absolute number
Sub VBA_Abs_Function_Ex1()

    'Variable declaration
    Dim iValue As Integer
    Dim vResult As Variant
    
    iValue = -4
        
    vResult = Abs(iValue)
        
    MsgBox "Convert a number(-4) to an absolute value : " & vResult, vbInformation, "VBA Abs Function"
    
End Sub

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

Example 2: Convert a value(4) to an absolute number

Here is a simple example of the VBA Abs function. This below example converts a value(4) to an absolute number. The below macro code returns an output as 4.

'Convert a value(4) to an absolute number
Sub VBA_Abs_Function_Ex2()

    'Variable declaration
    Dim iValue As Integer
    Dim vResult As Variant
    
    iValue = 4
        
    vResult = Abs(iValue)
        
    MsgBox "Convert a number(4) to an absolute value : " & vResult, vbInformation, "VBA Abs Function"
    
End Sub

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

Example 3: Convert a value(0) to an absolute number

Here is a simple example of the VBA Abs function. This below example converts a value(0) to an absolute number. The below macro code returns an output as 0.

'Convert a value(0) to an absolute number
Sub VBA_Abs_Function_Ex3()

    'Variable declaration
    Dim iValue As Integer
    Dim vResult As Variant
    
    iValue = 0
        
    vResult = Abs(iValue)
        
    MsgBox "Convert a number(0) to an absolute value : " & vResult, vbInformation, "VBA Abs Function"
    
End Sub

Output: Here is the screen shot of the third example output.
VBA Abs Function

Example 4: Convert a string(Text) to an absolute number

Here is a simple example of the VBA Abs function. This below example converts a string(Text) to an absolute number. The below macro code returns an error. The Abs function converts only numeric values not string.

'Convert a value("Text") to an absolute number
Sub VBA_Abs_Function_Ex4()

    'Variable declaration
    Dim sValue As String
    Dim vResult As Variant
    
    sValue = "Text"
        
    vResult = Abs(sValue)
        
    MsgBox "Convert a string('Text') to an absolute value : " & vResult, vbInformation, "VBA Abs Function"
    
End Sub

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

Example 5: Convert a value(Null) to an absolute number

Here is a simple example of the VBA Abs function. This below example converts a value(Null) to an absolute number. This function returns an output as ‘Null’.

'Convert a value(Null) to an absolute number
Sub VBA_Abs_Function_Ex5()

    'Variable declaration
    Dim iValue
    Dim vResult As Variant
    
    iValue = Null
        
    vResult = Abs(iValue)
        
    MsgBox "Convert 'Null' to an absolute value : " & vResult, vbInformation, "VBA Abs Function"
    
End Sub

Output: Here is the screen shot of the fifth example output.
VBA Abs Function

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

totn Excel Functions


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

Description

The Microsoft Excel ABS function returns the absolute value of a number.

The ABS 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 ABS 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 ABS function in Microsoft Excel is:

ABS( number )

Parameters or Arguments

number
A numeric value used to calculate the absolute value.

Returns

The ABS function returns a numeric 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 ABS function examples and explore how to use the ABS function as a worksheet function in Microsoft Excel:

Microsoft Excel

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

=ABS(A1)
Result: 210.67

=ABS(A2)
Result: 2.9

=ABS(A3)
Result: 3

=ABS(-4.5)
Result: 4.5

=ABS(-210.67)
Result: 210.67

=ABS(5)
Result: 5

=ABS(2-10)
Result: 8

Example (as VBA Function)

Now, let’s look at more Excel ABS examples and explore how to use the ABS function in Excel VBA code. For example:

Dim LNumber As Double

LNumber = Abs (-210.6)

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

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

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

  • 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.

Функция Abs

Abs(Number)

Функция Abs(Absolute) служит для вычисления абсолютного значения(модуля) числа. Абсолютное значение числа — это положительная величина, например абсолютное значение числа -7 равно 7

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

В результате действия функции Abs возвращается значение, тип которого совпадает с типом переданного аргумента и равняется абсолютному значению указанного в аргументе числа. Если аргумент имеет тип String, который может быть преобразован в число, тогда возвращается значение типа Double

Параметры

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

Пример

Dim A,B
A=Abs(10.7) ' возвращается 10.7
B=Abs(-17.4) ' возвращается 17.4

Категория
Математические функции

Понравилась статья? Поделить с друзьями:
  • Что такое doi в word
  • Что такое abex all to word converter
  • Что такое docx word 2007
  • Что такое 228 excel
  • Что такое displayalerts в excel