0

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

4
  • What is probably happening is, you run the vars sub and it saves "test" to xxxx, then the script stops running. Once the script stops, all your variables disappear - nothing is saved. You would need to call vars within the CommandButton1_Click sub - if you really need to save a value between runs of the script, either save it in a cell (if using excel) or in a table (in Access). Commented Jul 10, 2014 at 17:30
  • 1. Where did you call subroutine 'vars'? 2. where is xxxx defined? your code will work if you define properly, set the value, then reference. Commented Jul 10, 2014 at 17:36
  • thanks for the comments. @Acantud yes i need to call xxxx each time i need it (i am using excel and xxxx will define the last empty row in a column and i will use this var in many place so i dont wont to declare it each time i'll use). Commented Jul 11, 2014 at 7:40
  • @Wayne G.Dunn : subroutine vars is coded in main userform code and xxxx is defined on the same place just inside vars sub and just in the begining of userform code i declared a public xxxx. Commented Jul 11, 2014 at 7:40

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks i will use this method, call the sub vars in each subroutine where i need xxxx var.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.