Introduction | Example | Tutorial | Applications | Comments
Introduction - VBA Absolute Value
This VBA tutorial shows you how to take the absolute value of a number with the VBA Abs function. The VBA Abs function will return the absolute value of a number, variable or formula in your macro. The VBA Abs function accepts one argument - a number - and will return the magnitude of that number by ignoring its sign.
Keep exercising your macro skills and you too can develop VBA Abs! See what I did there?
Okay, okay. Let’s look at an example.
Example - VBA Absolute Value
VBA Abs Function
Sub VBA_Absolute_Value() Dim d1 As Double Dim d2 As Double Dim d3 As Double d1 = 1.5 d2 = -0.8 d3 = Abs(d1 * d2) Debug.Print d3 'Yields +1.2 End Sub
Becoming a VBA expert isn't hard
Over 5000 members are improving their VBA skills for free with our email tutorials. Why don't you join them? Our experts share time-saving VBA tips and we'll give you access to our huge macro library - it's sure to speed up your macro development.
Tutorial - VBA Absolute Value
How to find the absolute value in VBA
First, a refresher on what the absolute value of a number is. The absolute value of a number is a mathematical term meaning the magnitude of a number, ignoring the sign. In other words, the absolute value of a number is always the positive equivalent of the number representing how for away that number is from zero.
The VBA Abs function strips the sign from your numbers or numerical expressions to return the absolute value. To do that, the Abs function accepts one argument: a number. The number can be a variable or even a formula that produces a numeric result. In other words, any numeric expression will do. Here’s the syntax for the Abs function:
In the example above, the “Number” argument is the product of the variables
Common Error with the Abs function
If you accidentally pass the Abs function a string or other non-numeric value, you will get a “Run-time error ‘13’ Type Mismatch” error.
With that said, the Abs function isn’t dumb. If you try to take the absolute value of a string that represents a number, it will properly process the string as a number and return the absolute value. Here’s an example to demonstrate what I mean:
Sub VBA_Abs_String() Debug.Print Abs("-5.4") 'Yields +5.4 End Sub
You’ll want to use the VBA Abs function anytime you need to absolute value of a number. It’s a good function to use when you’re passing an argument to the VBA Sqr function since you can’t take the square root of a negative number.
If you liked this VBA tutorial, I hope you’ll shop my Excel Add-ins store to show your support for wellsr.com. Without revenue from great readers like you, it’s difficult to grow the site and reach more users.