Cannabiz
Cannabiz

Reputation: 35

VBA code using variable without defining it

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!

Upvotes: 2

Views: 976

Answers (1)

user4039065
user4039065

Reputation:

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.

Upvotes: 5

Related Questions