Abs Function

Named Arguments

No

Syntax

result = Abs(number)

number

Use: Required

Data Type: Any valid numeric expression

The number whose absolute value is to be returned.

Return Value

The absolute value of number. The data type is the same as that passed to the function.

Description

Returns the absolute value of a number (i.e., its unsigned magnitude). For example, Abs(-1) and Abs(1) both return 1. If number contains Null, Null is returned; if it's an uninitialized variable, zero is returned.

Rules at a Glance

Only numeric values can be passed to the Abs function.

Example

In this example, the LineLength function determines the length of a line on the screen. If the line runs from left to right, X1 is less than X2, and the equation (X2-X1) returns the length of the line. If, however, the line runs from right to left, X1 is greater than X2, and a negative line length is returned. As you know, in most circumstances, it doesn't matter which way a line is pointing; all you want to know is how long it is. Using the Abs function allows you to return the same figure whether the underlying figure is negative or positive.

Function LineLength(X2 as Integer) as Integer

    Dim X1 As Integer

    X1 = 100
    LineLength = Abs(X2 - X1)

End Function

Programming Tips and Gotchas

Because the Abs function accepts only numeric values, you may want to check the value you pass to Abs using the IsNumeric function to prevent generating an error. This is illustrated in the following code snippet:

If IsNumeric(vExtent) ...

Get VB & VBA in a Nutshell: The Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.