Access для Microsoft 365 Access 2021 Access 2019 Access 2016 Access 2013 Access 2010 Access 2007 Еще…Меньше
Возвращает значение того же типа, который был передан в функцию, указывая абсолютное значение числа.
Синтаксис
Abs(
number
)
Требуемая аргумент может быть любой допустимой числовое выражение. Если число содержит NULL, возвращается NULL; если это неинициализированный переменная, возвращается ноль.
Замечания
Абсолютная величина числа — это его неподписаное значение. Например, ABS(-1) и ABS(1) возвращают 1.
Примеры запросов
|
|
SELECT Abs([Discount]) AS Expr1 FROM ProductSales; |
Возвращает абсолютные значения поля Discount из таблицы ProductSales в столбце Expr1, преобразует отрицательное значение в положительные (и оставляет положительные числа без изменений). |
SELECT Abs([Discount]/[SalePrice]) AS DiscountPercent FROM ProductSales; |
Вычисляет все значения в поле «Скидка» в процентах от поля «SalePrice» и отображает в столбце DiscountPercent. |
Пример VBA
Примечание: В примерах ниже показано, как использовать эту функцию в модуле Visual Basic для приложений (VBA). Чтобы получить дополнительные сведения о работе с VBA, выберите Справочник разработчика в раскрывающемся списке рядом с полем Поиск и введите одно или несколько слов в поле поиска.
В этом примере функция Abs используется для вычисления абсолютного значения числа.
Dim MyNumber
MyNumber = Abs(50.3) ' Returns 50.3.
MyNumber = Abs(-50.3) ' Returns 50.3.
Нужна дополнительная помощь?
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.
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.
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.
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.
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.
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 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!
Learn More!
ТРЕНИНГИ
Быстрый старт
Расширенный Excel
Мастер Формул
Прогнозирование
Визуализация
Макросы на VBA
КНИГИ
Готовые решения
Мастер Формул
Скульптор данных
ВИДЕОУРОКИ
Бизнес-анализ
Выпадающие списки
Даты и время
Диаграммы
Диапазоны
Дубликаты
Защита данных
Интернет, email
Книги, листы
Макросы
Сводные таблицы
Текст
Форматирование
Функции
Всякое
Коротко
Подробно
Версии
Вопрос-Ответ
Скачать
Купить
ПРОЕКТЫ
ОНЛАЙН-КУРСЫ
ФОРУМ
Excel
Работа
PLEX
© Николай Павлов, Planetaexcel, 2006-2022
info@planetaexcel.ru
Использование любых материалов сайта допускается строго с указанием прямой ссылки на источник, упоминанием названия сайта, имени автора и неизменности исходного текста и иллюстраций.
Техническая поддержка сайта
ООО «Планета Эксел» ИНН 7735603520 ОГРН 1147746834949 |
ИП Павлов Николай Владимирович ИНН 633015842586 ОГРНИП 310633031600071 |