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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With