PDA

View Full Version : [SOLVED] Set value to variable in vba to use different sub



vmjamshad
05-23-2018, 11:06 PM
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!

mattreingold
05-24-2018, 10:49 AM
It appears as if you have the answer... declaring 'i' as public should allow this, no?

georgiboy
05-25-2018, 05:38 AM
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

vmjamshad
05-26-2018, 08:36 PM
This helps. Thanks!