Consulting

Results 1 to 4 of 4

Thread: Set value to variable in vba to use different sub

  1. #1

    Set value to variable in vba to use different sub

    Hi, Is there a way that I can Set a value to a variable and use that value for different sub.
    Public i As Long
    
    Sub test1()
        i = 5
        MsgBox i
    End Sub
    
    Sub test2()
        i = 5
        MsgBox i
    End Sub
    and what I am looking for is:
    Public i As Long
    i=5
    
    Sub test1()
        MsgBox i
    End Sub
    
    Sub test2()
        MsgBox i
    End Sub
    Thank u!

  2. #2
    It appears as if you have the answer... declaring 'i' as public should allow this, no?

  3. #3
    Moderator VBAX Master georgiboy's Avatar
    Joined
    Mar 2008
    Location
    Kent, England
    Posts
    1,190
    Location
    I do believe you can only assign a constant to a value outside of a sub:
    Public Const i = 5
    
    Sub test1()
        MsgBox i
    End Sub
    
    
    Sub test2()
        MsgBox i
    End Sub
    Another option might be to create global variables and assign values to them using an Auto_open sub.

    Standard module:
    Global i As Long
    
    Sub test1()
        MsgBox i
    End Sub
    
    
    Sub test2()
        MsgBox i
    End Sub
    ThisWorkbook module:
    Private Sub Workbook_Open()
        i = 1
    End Sub
    Hope this helps
    Last edited by georgiboy; 05-25-2018 at 05:56 AM. Reason: typo
    Click here for a guide on how to add code tags
    Click here for a guide on how to mark a thread as solved

    Excel 365, Version 2403, Build 17425.20146

  4. #4
    This helps. Thanks!

Posting Permissions

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