gpt4 book ai didi

vba - 变量未定义编译器错误

转载 作者:行者123 更新时间:2023-12-02 10:40:49 28 4
gpt4 key购买 nike

我是 Excel 的长期狂热用户,但我才刚刚开始学习 VBA。我正在使用以下代码,但在尝试运行 Sub test 时出现错误:

Compile Error:Variable not defined

你能帮我找出问题所在吗?

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

最佳答案

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

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

Sub test()
Dim answer As Variant
answer = toCentigrade(55)
MsgBox answer
End Sub

编辑

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

如果您正确输入所有内容,您的示例将变为:

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

关于vba - 变量未定义编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27694994/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com