Excel-VBA:需要变量声明吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4205560/
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-11 12:18:49  来源:igfitidea点击:

Excel-VBA: Variable declaration necessary?

vbaexcel-vbavariable-declarationexcel

提问by Carlos

Would it be wrong if write the following code

写下面的代码会不会出错

Sub Something()
 Dim i As integer
 Dim xRange As Range
 Dim yRange As Range

 Set xRange= Range("x_table")
 Set yRange= Range("y_table")

 For i = 1 To xRange.Columns.Count
    xRange.Columns(i) = Application.Sum(y_table.Columns(i))
 Next i
End Sub

without specifically declaring each of the variables? Like bellow;

没有特别声明每个变量?像下面这样;

Sub Something()
 Set xRange= Range("x_table")
 Set yRange= Range("y_table")

 For i = 1 To xRange.Columns.Count
    xRange.Columns(i) = Application.Sum(y_table.Columns(i))
 Next i
End Sub

回答by N0Alias

If Option Explicit isn't turned on you cando it that way, but I wouldn't recommend it because then you're relying on the framework to guess at the type of variable it is dealing with, which could cause unexpected results.

如果 Option Explicit 没有打开,你可以这样做,但我不会推荐它,因为那样你就依赖于框架来猜测它正在处理的变量类型,这可能会导致意外的结果。

回答by BradC

It works fine, until it doesn't.

它工作正常,直到它没有。

Your examples are pretty simple, but its entirely possible to come up with situations that cause problems.

您的示例非常简单,但完全有可能提出导致问题的情况。

Better to declare all so that you don't risk running into ambiguity at runtime.

最好全部声明,以免在运行时遇到歧义。

I'm also partial to MikeD's comment regarding autocomplete.

我也偏爱 MikeD 关于自动完成的评论。