vba 变量未定义编译器错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27694994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 09:14:56  来源:igfitidea点击:

Variable Not Defined Compiler Error

vbacompiler-errors

提问by Alyss

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:

我是一个长期的 Excel 狂热用户,但我才刚刚开始学习 VBA。我正在使用以下代码,但在尝试运行时出现错误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

回答by Jason Faulkner

You have Option Explicitturn on which means you mustdeclare your variables before using them.

您已Option Explicit打开,这意味着您必须在使用变量之前声明它们。

In Sub test, you are missing a declaration for answer. Adding this should fix it:

在 中Sub test,您缺少 的声明answer。添加这个应该可以解决它:

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.

由于您是 VBA 新手,您可能需要考虑同时键入变量和函数返回值。您不必这样做(并且所有内容都将被视为Variant),但这是一种很好的做法。

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

回答by bilbo_strikes_back

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