Reputation: 31
I am a long time avid Excel user but am just starting to learn VBA. I am using the following code but am getting an error when I try to run Sub test
:
Compile Error:Variable not defined
Can you help me figure out what is wrong?
Option Explicit
Function toFarenheit(degrees)
toFarenheit = (9 / 5) * degrees + 32
End Function
Function toCentigrade(degrees)
toCentigrade = (5 / 9) * degrees - 32
End Function
Sub test()
answer = toCentigrade(55)
MsgBox answer
End Sub
Upvotes: 3
Views: 72790
Reputation: 1
Don't listen to the professionals. The answer for the ordinary person is: remove statement "option explicit", probably at the top somewhere. Easy, and correct for you and me.
Upvotes: -3
Reputation: 6578
You have Option Explicit
turn on which means you must declare your variables before using them.
In Sub test
, you are missing a declaration for answer
. Adding this should fix it:
Sub test()
Dim answer As Variant
answer = toCentigrade(55)
MsgBox answer
End Sub
Edit
Since you are new to VBA, you might want to consider typing both your variables and function returns. You don't have to do this (and everything will be treated as a Variant
), but it is good practice.
If you type everything properly, your example would become:
Option Explicit
' Accept a double value and return a double type value.
Function toFarenheit(degrees As Double) As Double
toFarenheit = (9 / 5) * degrees + 32
End Function
Function toCentigrade(degrees As Double) As Double
toCentigrade = (5 / 9) * degrees - 32
End Function
Sub test()
' Variable type matches what the function will return.
Dim answer As Double
answer = toCentigrade(55)
MsgBox answer
End Sub
Upvotes: 7
Reputation: 591
I tested this to convert to farenheit
The function is as follows
Function ToFarenheit(Degrees As Double)
ToFarenheit = (9 / 5) * Degrees + 32
End Function
The sub is as follows
Sub TestFunction()
MsgBox ToFarenheit(0)
End Sub
Upvotes: -3