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
Best Solution
You have
Option Explicit
turn on which means you must declare your variables before using them.In
Sub test
, you are missing a declaration foranswer
. Adding this should fix it: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: