3

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

2 Answers 2

14

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.

Sign up to request clarification or add additional context in comments.

9 Comments

@DaMartyr, thanks! if you will be a uni professor, will you mark me down for not declaring?
start typing "xrange." and watch the methods and properties expanding on the dot in your 1st example while it does not in your 2nd example - this will give you help and confidence when you code - that's why I always qualify my objects first. There is hardly any case where you must use late binding
Yep. It is a bad practice. In medium/large projects you may enter deep waters without Option Explicit.
@Carlos Dim i, j, k As Integer ... logicamente
@belisarius--no, No, NO, a thousand times NO! That's one of the traps of VB-based languages (VB & VBA). "Dim i, j, k As Integer" will get you ONE integer (k) and two Variants (i & j). You can do it all on one line, thus: "Dim i As Integer, j As Integer, k As Integer"
|
7

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.