Question

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
Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top