Excel-VBA:需要变量声明吗?
如果编写下面的代码
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
而不具体声明每个变量会不会是错误的?就像下面这样;
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果未打开 Option Explicit,您可以这样做,但我不会推荐它,因为这样您就依赖框架来猜测它正在处理的变量的类型,这可能会导致意想不到的结果。
If Option Explicit isn't turned on you can do 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.
它工作得很好,直到它不起作用。
你的例子非常简单,但完全有可能提出导致问题的情况。
最好全部声明,这样就不会在运行时遇到歧义。
我也偏向 MikeD 关于自动完成的评论。
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.