Thread: Pi in VBA?
View Single Post
  #27   Report Post  
Posted to microsoft.public.excel.programming
joeu2004[_2_] joeu2004[_2_] is offline
external usenet poster
 
Posts: 829
Default Pi in VBA?

"Auric__" wrote:
I just assign it to a constant if I need it:
Const PI = 3.14159265358979


If you want to ensure a match with Excel PI(), use the following constant
expression:

Const pi As Double = 3.14159265358979 + 3.1E-15

Or you could write:

Const pi As Double = "3.1415926535897931"

since VBA converts all digits, not just the first 15 significant digits as
Excel does.

FYI, I avoid writing the following:

Const pi As Double = 3.1415926535897931

It works initially. But VBA displays the statement as

Const pi As Double = 3.14159265358979

and the value of pi will be changed to 3.14159265358979 if we edit the line
(e.g. append a comment) and perhaps under other conditions that cause VBA to
re-interpret the statement.

To confirm the differences, try the following macro.

Sub testit()
Const pi As Double = "3.1415926535897931"
Const pi1 As Double = 3.14159265358979
Dim pi2 As Double, pi3 As Double
Range("a1").Clear
Range("a1").Formula = "=PI()"
pi2 = WorksheetFunction.pi()
pi3 = 4 * Atn(1)
MsgBox Format(pi1 - pi, "0.0000E+0") & _
vbNewLine & (pi1 = pi) & _
vbNewLine & (pi1 = Range("a1")) & _
vbNewLine & Format(pi - pi2, "0.0000E+0") & _
vbNewLine & Format(pi3 - pi2, "0.0000E+0") & _
vbNewLine & Format(pi - pi3, "0.0000E+0") & _
vbNewLine & (pi = pi2) & _
vbNewLine & (pi = Range("a1"))
End Sub