Microsoft Access (2010) for Developers: How to declare public variables?


I declare and use the same dozen or so variables for so many different things on the same form and currently my code looks like:
Private Sub 1()
DIM str1 as string
'... 11 more
'Code
End Sub
Private Sub 2()
DIM str1 as string
'... 11 more
'Code
End Sub
Private Sub 3()
DIM str1 as string
'... 11 more
'Code
End Sub
'and so on..

How can I do something like:
Public Sub DecareVars() '<-????????
Dim str1 as String
'... 11 more
End Sub
Private Sub 1()
'code
End Sub
Private Sub 2()
'code
End Sub
Private Sub 3()
'code
End Sub

 

Also, what happened to the normal forum? I can't fi

July 5th, 2013 9:43am

When you declare variables within a procedure (Sub), the variables are local to that procedure: they will not be recognized outside the procedure.

You can make a variable known to all procedures within the same module by declaring it at the top of the module, before all procedures, e.g.

Option Compare Database
Option Explicit

Dim str1 As String
Dim str2 As String
' ...

Private Sub MySub1()
    str1 = "Hello World"
End Sub

Private Sub MySub2()
    MsgBox str1
End Sub

Variables declared at the top of a module with Dim or with Private will *not* be recognized outside that module: code in other modules cannot "see" them.

To make a variable known to all code in the database, declare it at the top of a standard module (the kind you create by selecting Insert > Module) with the keyword Public. For example:

Option Compare Database
Option Explicit

Public str1 As String
Public str2 As String
' ...

See A matter of scope: visibility of code elements for more info.

 

Free Windows Admin Tool Kit Click here and download it now
July 5th, 2013 10:07am

So helpful, thank you so much.
July 5th, 2013 10:33am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics