+ Reply to Thread
Results 1 to 5 of 5
  1. #1
    Registered User
    Join Date
    08-28-2007
    Posts
    48

    A variable which is used by several subs in a worksheet but is not global?

    Hi,

    I am working on a workbook which uses a large number of variables. I am trying to keep them as "local" as possible to keep it simple.

    Some of my variables are local to the subs they're used in.
    Some are global as they're used by subs in several sheets.
    A third type of variable is used by several subs all belonging to the same sheet.

    Is there a way of declaring them so they're known by all subs in that sheet, but not by every sub in the workbook?

    Cheers,

    Lotte

  2. #2
    Forum Moderator shg's Avatar
    Join Date
    06-21-2007
    Location
    The Great State of Texas
    MS-Off Ver
    2003, 2007
    Posts
    25,138
    Just declare them at the top of the module (after Option Explicit) using Dim.

    You can only declare public variables in a code module, not in a sheet, workbook, forms, or class module.
    Microsoft MVP - Excel
    Entia non sunt multiplicanda sine necessitate

  3. #3
    Registered User
    Join Date
    08-28-2007
    Posts
    48
    Hi Shg,
    Thanks for your reply.
    The subs which use these variables are not in a module but in the code that corresponds to individual sheets. Is there a way of declaring these variables so they are known to all the subs in that sheet (but not the subs in other sheets, or modules)?
    Cheers,
    Lotte

  4. #4
    Forum Guru Andy Pope's Avatar
    Join Date
    05-10-2004
    Location
    Essex, UK
    MS-Off Ver
    2003 & 2007 & 2010
    Posts
    10,944
    As shg said declare the variable at the top of the relevant module.

    Code Module
    Code:
    Public X
    Sub Test()
    
        X = 1
        Sheet1.X = 2
        
        MsgBox X, , "Project Level X"
        MsgBox Sheet1.X, , "Sheet Level X"
        
        Sheet1.TestMe
    
        MsgBox X, , "Project Level X"
        MsgBox Sheet1.X, , "Sheet Level X"
        
    End Sub

    Sheet Code Module
    Code:
    Public X
    
    Public Sub TestMe()
        
        X = X + 2
        
        MsgBox X, , "Sheet Level X"
        
    End Sub
    Cheers
    Andy
    www.andypope.info

  5. #5
    Registered User
    Join Date
    08-28-2007
    Posts
    48
    Shg and Andy,
    Thanks!
    Lotte

Thread Information

Users Browsing this Thread

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

Tags for this Thread

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.2.0