+ Reply to Thread
Results 1 to 3 of 3

Placement in Code of Decarled Variables

  1. #1
    Registered User
    Join Date
    07-30-2012
    Location
    USA
    MS-Off Ver
    Excel 2007
    Posts
    38

    Placement in Code of Decarled Variables

    Hello,

    I am going through some macros, and I have noticed that some variables are declared at the beginning of a subroutine and used later in the routine (i.e. they are declared at the beginning, but might not be used until the end of the subroutine). Other variables, however, are declared immediately before being used. Examples are below:

    'declare variables at the beginning of the subroutine, but used at the end of the subroutine
    Dim questionanswerws As Worksheet
    Dim questionmapWS As Worksheet
    Dim demomapws As Worksheet
    Dim respondentint As Integer
    Dim responseint As Integer
    Dim responseWS As Worksheet
    Dim respondentWS As Worksheet

    'declared the variables and used immediately
    Dim ws As Worksheet
    For Each ws In Worksheets
    ws.Range("A1:z1").EntireColumn.AutoFit
    ws.AutoFilterMode = False
    Next ws

    My question is: does it matter where in the subroutine these are declared? Would there ever be a reason why you would not declare all variables at the beginning of the subroutine?

    Thank you!

  2. #2
    Forum Expert Bob Phillips's Avatar
    Join Date
    09-03-2005
    Location
    Wessex
    MS-Off Ver
    Office 2003, 2010, 2013, 2016, 365
    Posts
    3,284

    Re: Placement in Code of Decarled Variables

    They have to be declared before they are used, but other than that it does not matter.

    Personally, I like to declare them all up-front.

  3. #3
    Registered User
    Join Date
    07-30-2012
    Location
    USA
    MS-Off Ver
    Excel 2007
    Posts
    38

    Re: Placement in Code of Decarled Variables

    Thank you! That is what I thought.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1