Khaled_Jamel
Khaled_Jamel

Reputation: 101

cannot use public var vba

i am wrting a vba code where i will set some public var to use in many subs vars declared in userform code like this

public xxxx as string

sub vars()
xxxx = "test"
end sub

Private Sub CommandButton1_Click()
' test button 
MsgBox ("pub var is " & xxxx)
End Sub

when i click in test buton the msg box is blank looks like it cant see the pub var aney ideas where is the problem (even if i set public xxxx as srtring in the code of a module or thisworkbook i get the same result) thanks

Upvotes: 0

Views: 108

Answers (1)

djikay
djikay

Reputation: 10628

It looks obvious to me, so I may have misunderstood the question.

You're not calling vars() anywhere, so the string xxxx is initialised to its default value (blank). If you change your code to call vars() as follows:

Private Sub CommandButton1_Click()
  ' call vars() to set the string value
  vars

  ' test button
  MsgBox ("pub var is " & xxxx)
End Sub

then it will work as you expect.

In my test, even if I call vars() first on its own and then your button_click as you posted it, the value of xxxx is set correctly. Obviously, this value won't survive closing Excel and restarting it. In that case, you'll need to save its value externally somewhere and reload it when Excel is restarted.

Upvotes: 2

Related Questions