Carlos
Carlos

Reputation: 5445

Excel-VBA: Variable declaration necessary?

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

Upvotes: 3

Views: 10470

Answers (2)

BradC
BradC

Reputation: 39946

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.

Upvotes: 7

NoAlias
NoAlias

Reputation: 9193

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.

Upvotes: 14

Related Questions