Using Excel VBA - problems in passing a global variable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tryinghard
    New Member
    • Nov 2013
    • 7

    Using Excel VBA - problems in passing a global variable

    I have many subroutines that get called from various events on multiple excel worksheets,
    All I want to do is identify which subs have been used.
    I wish to set a variable in each sub and take action in another sub depending on its value:
    Purch does not get passed. Helllllp

    sub calc()
    dim Purch as integer

    if Purch = 1 then
    'perform some action
    elseif Purch = 2 then
    ' perform som different action
    'etc
    end if
    end sub

    sub action1()
    Purch = 1
    end sub

    sub action2()
    Purch = 2
    end sub

    'etc for many such subs.
  • Killer42
    Recognized Expert Expert
    • Oct 2006
    • 8429

    #2
    I believe what you need to do is define Purch at the module level. If you define it within a Sub, it only exists as a local variable within that sub.

    For example...
    Code:
    [B]Public Purch As Integer[/B] ' Global variable.
    
    Sub Calc()
      If [B]Purch[/B] = 1 then
        ' Perform some action
      ElseIf [B]Purch[/B] = 2 then
        ' Perform some different action
      'etc
      End if
    End Sub
    
    Sub Action1()
      [B]Purch[/B] = 1
    End Sub
    Note, defining the variable as Public also allows it to be used by code in other modules. Using Private would restrict it to just this module.
    Last edited by Killer42; Nov 23 '13, 02:07 AM. Reason: Just removed a comma

    Comment

    • tryinghard
      New Member
      • Nov 2013
      • 7

      #3
      Ahh, Thanks Killer42, I thought there must be a simple answer.
      I've just stumbled across another little problem that the Excel VBA Help is less than useful with. It's to do with Formula = in VBA code.
      I think I better enter it as a new Problem, hope you can help me with that also.

      Comment

      Working...