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

发布于 2024-10-03 11:14:54 字数 539 浏览 1 评论 0原文

如果编写下面的代码

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

嘿嘿嘿 2024-10-10 11:14:54

如果未打开 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.

九局 2024-10-10 11:14:54

它工作得很好,直到它不起作用。

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

最好全部声明,这样就不会在运行时遇到歧义。

我也偏向 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文