首页 > 解决方案 > 如何在 sub b 中使用 sub a 中的值

问题描述

在第一个 sub 中获得的值不会延续到下一个,我该怎么做?

这只是代码的一小部分,还有许多其他变量和其他用户输入不允许我组合 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

例如 fromd 是 2019 年 1 月,tod 是 2019 年 3 月。理想的结果是范围 A1 中的值是“对于 2019 年 1 月至 2019 年 3 月的日期:”提前致谢!

标签: excelvba

解决方案


如您在此示例中所见,在过程之外声明变量非常简单:

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

我已经启动了test3(),在将值 4 放入 cellA1之后,我已经运行test1()了两次和test2()一次。然后我在 中放了一个断点test1(),在即时窗口中,我输入了:

? a

回应是 7。


推荐阅读