变量未定义的编译器错误 [英] Variable Not Defined Compiler Error

查看:136
本文介绍了变量未定义的编译器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Excel的狂热用户,但是我刚刚开始学习VBA。我正在使用以下代码,但在尝试运行子测试时出错:

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


推荐答案

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

You have Option Explicit turn on which means you must declare your variables before using them.

子测试中,您缺少 answer 的声明。添加它应该可以解决这个问题:

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






编辑

由于您是VBA的新手,因此您可能需要考虑同时输入变量和函数返回值。您不必执行此操作(所有内容都将被视为 Variant ),但这是一个好习惯。

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

这篇关于变量未定义的编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆