5

I am new to VBA programming and had a doubt which may be quite simple for you.

How do we set a variable in one sub which can be used in another?

I tried using global variable but it didnt work for me. Thank you

VikkyB
  • 1,440
  • 4
  • 16
  • 26

1 Answers1

10

Here is an example of how I have created a variable in one sub and used it in another:

    Private Sub txtLastName_LostFocus()
    FirstName = Me.txtFirstName.Value
    LastName = Me.txtLastName.Value
    FullName = FirstName & " " & LastName
    sayHelloToTheUser (FullName)
    End Sub

    Private Sub sayHelloToTheUser(name As String)
    MsgBox "Hello " & name
    End Sub

Essentially, you must pass it through using another sub and having it take the arguments that are necessary. This is the main way that I pass arguments through.

Mardin Yadegar
  • 437
  • 4
  • 10
  • 7
    +1 for **not** using a global variable and passing parameters. In the vast majority of cases, this is how it's done. Having many, many globally-scoped variables is a *code smell* that eventually leads to hard-to-follow-and-debug code. – Mathieu Guindon Aug 01 '13 at 16:16