Excel-VBA: Variable declaration necessary?

calendar_today Asked Nov 17, 2010
thumb_up 12 upvotes
history Updated April 16, 2026

Question posted 2010 · +2 upvotes

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

Accepted answer +12 upvotes

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.

Excel VBA objects referenced (5)

  • Application — Using events with the Application object
  • Application — Working with Other Applications
  • Columns.Count — Count function (Microsoft Access SQL)
  • Columns.Count — Count the number of records in a DAO Recordset
  • Range — Refer to Cells by Using a Range Object

Top excel-vba Q&A (6)

+12 upvotes ranks this answer #45 out of 136 excel-vba solutions on this site .