Scientific notation is a way of writing very large or very small numbers in a compact and consistent format. It is often used in fields such as engineering, chemistry, physics, and mathematics.
In Excel, you can use scientific notation to display numbers in cells or charts, or you can use VBA to manipulate numbers in scientific notation.
I will show you how to write scientific notation in VBA using the Format function, which allows you to control the string representation of numbers. I will also show you how to use scientific notation in calculations and comparisons.
The Format function
The Format function takes a number and a format string as arguments and returns a formatted string. You can use the “Scientific” format string to convert a number into scientific notation, or you can use a custom format string to specify the number of decimal places and the exponent symbol.
For example, the following code converts the number 123456789 into scientific notation using the “Scientific” format string:
Dim num As Double
num = 123456789
Dim sci As String
sci = Format(num, "Scientific")
Debug.Print sci
'Output: 1.23E+08
The following code converts the same number into scientific notation using a custom format string that shows four decimal places and uses “e” instead of “E” as the exponent symbol:
Dim num As Double
num = 123456789
Dim sci As String
sci = Format(num, "0.0000e+00")
Debug.Print sci
'Output: 1.2346e+08
You can also use the Format function to convert a string in scientific notation into a number by using the Val function, which returns the numerical value of a string.
For example, the following code converts the string “3.21E-04” into a number:
Dim sci As String
sci = "3.21E-04"
Dim num As Double
num = Val(sci)
Debug.Print num
'Output: 0.000321
Using scientific notation in calculations and comparisons
You can use numbers in scientific notation in calculations and comparisons as long as they are stored as numbers and not as strings. If you store them as strings, you need to convert them into numbers first using the Val function.
For example, the following code calculates the product of two numbers in scientific notation:
Dim num1 As Double
num1 = 1.23E+08
Dim num2 As Double
num2 = 4.56E-09
Dim prod As Double
prod = num1 * num2
Debug.Print prod
'Output: 0.56088
The following code compares two numbers in scientific notation:
Dim num1 As Double
num1 = 1.23E+08
Dim num2 As Double
num2 = 4.56E-09
If num1 > num2 Then
Debug.Print "num1 is greater than num2"
ElseIf num1 < num2 Then
Debug.Print "num1 is less than num2"
Else
Debug.Print "num1 is equal to num2"
End If
'Output: num1 is greater than num2