2

I'm working on a macro that someone else wrote and am confused because they don't define a variable but are still using it. 1) is this possible and 2) how does excel/vba know what the variable is supposed to be? The variable used is "theCell" and there is no definition anywhere. Code below, and thanks:

Sub DoTheWork()

Sheets("All Data").Activate

ActiveSheet.Range("A2").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select

Set homebook = ActiveWorkbook
Set homeSheet = Sheets("All Data")
topRow = 2

Application.ScreenUpdating = False
'Application.ScreenUpdating = True

For Each theCell In Selection
    If (theCell.Value <> theCell.Offset(1, 0).Value) Then
        Range("A" & topRow & ":AS" & theCell.Row).Select
        Sheets("e-TAR").Select
        ActiveSheet.Copy
        Set copySheet = ActiveSheet
        Set copyBook = ActiveWorkbook

Thanks!

2
  • 2
    It is possible, it is considered bad practice. Unassigned variables are Variant, which means that excel makes it what is needed the first time it is used in this case it is a range variable. Commented Mar 11, 2016 at 17:03
  • 2
    Use of undefined variables is allowed if you don't have Option Explicit at the top of the module containing the code. It's good practise to always use that. Commented Mar 11, 2016 at 17:04

1 Answer 1

5

It doesn't know what it is supposed to be so it creates one on-the-fly as a variant type which can handle pretty much anything assigned to it including objects and arrays.

The 'best practise' is to put an Option Explicit statement at the top of each codesheet in the declarations area. This can be performed automatically upon the creation of each codesheet by setting the Require Variable Declaration within the VBE's Tools ► Options ► Editor property page.

This will avoid silly coding mistakes like misspellings as well as influencing you to use the correct variable type in the variable declaration.

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

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.