问题
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
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/4205560/excel-vba-variable-declaration-necessary