Using COS in VBA, incorrect value returned

G

Gnrnr

I did a bit of a search on this but when using VBA and having the
following equation the Cos function returns a value of 1 rather than
the correct -1. What am i doing wrong?

temp=cos(pi)

regards

Steve
 
D

Dave Peterson

Add
Option Explicit
at the top of your module and you'll see the problem.

Dim Pi As Double
Pi = 3.141592654
MsgBox Cos(Pi)
 
D

Dave Peterson

ps. You could use:

msgbox cos(application.pi)

==
or
Pi = 3.14159265358979
If you need that many decimal places.
 
G

Gnrnr

Add
Option Explicit
at the top of your module and you'll see the problem.

Dim Pi As Double
Pi = 3.141592654
MsgBox Cos(Pi)

Dave Peterson

Thanks Dave.

I'll give that a go. I thought that pi was a defined constant within
VBA though. I'm guessing it is something to do with the computer
having to think for me to create a constant on the fly so to speak?

Regards
Steve
 
D

Dana DeLouis

Just for fun... This is not ideal, but a fun attempt at using a Pi symbol in
vba.
You have to hold Alt key, then 0182. Plus, you have to use a little
imagination on the Pi symbol.

Sub Fun()
Dim ¶ As Double ' Alt+0182
¶ = [Pi()]
MsgBox Cos(¶)
End Sub
 
D

Dave Peterson

And just to clarify:

¶ = [Pi()]
is equivalent to:
¶ = application.evaluate("Pi()")

which could be replaced by:
¶ = application.pi

Sometimes using [] can be confusing.

Dana said:
Just for fun... This is not ideal, but a fun attempt at using a Pi symbol in
vba.
You have to hold Alt key, then 0182. Plus, you have to use a little
imagination on the Pi symbol.

Sub Fun()
Dim ¶ As Double ' Alt+0182
¶ = [Pi()]
MsgBox Cos(¶)
End Sub

--
Dana DeLouis

Gnrnr said:
Thanks Dave.

I'll give that a go. I thought that pi was a defined constant within
VBA though. I'm guessing it is something to do with the computer
having to think for me to create a constant on the fly so to speak?

Regards
Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top