0

I need to make a function that finds Cosine in Degrees. I am on Mac-OS Excel 2011

Function cosd(d)
    deg = (d * 3.14159265358979) / 180    
    cosd = WorksheetFunction.Cos(deg)
End Function

It still does not work.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Waleed
  • 59
  • 1
  • 1
  • 8
  • possible duplicate of [VBA sin() and cos() trouble](http://stackoverflow.com/questions/21971654/vba-sin-and-cos-trouble) – eirikdaude Apr 11 '15 at 23:16
  • On later versions of Excel there is a built-in `WorksheetFunction.Cosd()` – John Alexiou Apr 12 '15 at 00:18
  • If there is a native worksheetfunction with the same name as your function, that will probably explain the `#NAME`-error too. Otherwise I'm not sure what could be the reason for it. Maybe the wrong kind of data in the argument? – eirikdaude Apr 12 '15 at 00:31

1 Answers1

2

You are really close the only trouble with your function (well, besides that not declaring your variables is bad practice) is that Cos isn't a VBA function. Change your function to

Function cosd(d As Double) As Double
  cosd = Application.WorksheetFunction.Cos((d * Application.WorksheetFunction.Pi) / 180#)
End Function

and it should work just fine.

eirikdaude
  • 3,106
  • 6
  • 25
  • 50
  • It says "error:expected end of statement". I have pulled all my hair over this?! – Waleed Apr 11 '15 at 23:46
  • Whoops, forgot to add in a parantheses at the start of the statement, fixed now @WaleedKAl-Shaikhli – eirikdaude Apr 11 '15 at 23:47
  • Why not use the bult-in `Cos()` function defined in VBA? – John Alexiou Apr 11 '15 at 23:54
  • I cant get it to work. When I type "cosd(90)" in a cell the output is "#NAME?" – Waleed Apr 12 '15 at 00:00
  • @ja72 According to the original question, using the native `COS`-function didn't work. He's changed it now, so I can't check it again to see if there were any other problems, but I didn't see anything obvious. Could it possibly be that the `COS`-function needs to be preceded by `Math.`? Some googling seems to indicate this, but I am not at my work computer atm, so I can't check. – eirikdaude Apr 12 '15 at 00:06