How can I use values found in sub a in sub b

Viewed 46

The value obtained in the first sub does not carry onto the next, how do I go about doing so?

This is just a small part of the codes, there are many other variables and other user inputs that do not allow me to combine the subs.

Private Sub lbEY_AfterUpdate()

Dim sd As Date
Dim ed As Date
Dim fromd As String
Dim tod As String

sm = Month(DateValue("01-" & lbSM & "-1900"))
em = Month(DateValue("01-" & lbEM & "-1900"))

sd = DateSerial(lbSY, sm, 1)
ed = DateSerial(lbEY, em, 1)

    fromd = Format(sd, "mmmm yyyy")
    tod = Format(ed, "mmmm yyyy")

End Sub

Private Sub CommandButton2_Click()

Range("A1").Value = "For dates " & fromd & " to " & tod & ":"
'This prints out "For dates  to :"

End Sub

e.g. fromd is January 2019 and tod is March 2019. The ideal outcome would be for the value in Range A1 to be" For dates January 2019 to March 2019:" Thanks in advance!

1 Answers

Declaring a variable outside of a procedure is quite simple, as you can see in this example:

Dim a As Integer

Sub test1()
 a = a + 1
End Sub

Sub test2()
a = a + 1
End Sub

Sub test3()
a = Range("A1").Value
End Sub

I've launched test3(), after having put value 4 in cell A1, then I've run test1() two times and test2() one time. Then I put a breakpoint in test1(), and in the immediate window, I've entered:

? a

The response was 7.

Related