+ Reply to Thread
Results 1 to 3 of 3

carrying over variable values

Hybrid View

tryer carrying over variable values 09-07-2009, 06:02 AM
Andy Pope Re: carrying over variable... 09-07-2009, 06:14 AM
DonkeyOte Re: carrying over variable... 09-07-2009, 06:14 AM
  1. #1
    Valued Forum Contributor
    Join Date
    11-16-2004
    Location
    Devon UK
    MS-Off Ver
    2010
    Posts
    357

    carrying over variable values

    When I call a second subroutine (in the same module) from within the main code the values of my variables are not available in the second subroutine. I thought that variable values were available to any subroutines within the same module. I know I can declare tham as Public variables but then they will be available thoughout the whole project and this is not what I want.
    Is is perhaps because of the way I am declaring them : with Dim statements at the begining of the main sub ? or is there something specific I have to do?

    When stepping through the code I can see that a certain variable for example has a value of 6 in the main code but in the new sub this same variable is showing as 'empty'

  2. #2
    Forum Guru Andy Pope's Avatar
    Join Date
    05-10-2004
    Location
    Essex, UK
    MS-Off Ver
    O365
    Posts
    20,482

    Re: carrying over variable values

    If the variable is declared within a routine then it's scope is restricted to that routine.

    If you declare a private variable at the top of a module then it's scope is all routines within that module.

    If you declare a public variable at the top of a module then it's scope is all routines within all modules of that vba project.

    Private m_lngVar as long
    Cheers
    Andy
    www.andypope.info

  3. #3
    Forum Guru DonkeyOte's Avatar
    Join Date
    10-22-2008
    Location
    Northumberland, UK
    MS-Off Ver
    O365
    Posts
    21,531

    Re: carrying over variable values

    Sounds like you want something like below (note assumed based on your post you're not utilising Option Explicit)

    Module 1
    
    Dim strVar As String
    Sub One()
    strVar = "Hello World"
    Call Two()
    Call Three()
    End Sub
    
    Sub Two()
    MsgBox strVar
    End Sub
    Module 2
    
    Sub Three()
    MsgBox strVar
    End Sub
    strVar won't be accessible outside of Module 1

+ 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