使用VBA CommandButton值variables从用户窗体到模块

我知道,如果我们将一个variables命名为Public那么如果variables在End Sub之间传递了End Sub ,则variables可以保持其值。 但我的问题是,我有一个variables,从用户窗体中的commandnbutton获取它的值,每次我尝试从userform子项中设置这个variables时,都会收到编译错误。 我有一个月的列表框,select月份后按下命令button,macros开始。 我知道,只要H通过Ens Sub ,variables的值就会在subs之间移动,我也需要在其他的subs中使用这个variables值,我需要它是dynamic的,任何人都知道什么可以帮助我?

这是用户表单子:

  Public MainWB As Workbook Public VisualWB As Workbook Public VisualWS As Worksheet Public VacationWS As Worksheet Public HealingWS As Worksheet Public IllnessWS As Worksheet Public Lists As Worksheet Public MonthCol As Long Public MonthName As String Public MonthBefore As Long Public ColumnSpace As Long Public LR As Long Public LC As Long Public myExtension As String Public SecondPath As String Public Table As Range Public Names As Range Private Sub CommandButton1_Click() Application.ScreenUpdating = False Application.EnableEvents = False Application.DisplayAlerts = False Application.Calculation = xlManual Call initialize 'Here I have a lot of Code Unload UserForm1 Application.ScreenUpdating = True Application.EnableEvents = True Application.DisplayAlerts = True Application.Calculation = xlAutomatic End Sub 

这是模块子:

 Option Explicit Sub initialize() 'The variables will keep their value on all the subs MonthName = ListOfMonths.Value Set MainWB = ThisWorkbook Set VacationWS = MainWB.Worksheets(1) Set HealingWS = MainWB.Worksheets(2) Set IllnessWS = MainWB.Worksheets(3) Set Lists = MainWB.Worksheets("Lists") Set VisualWS = MainWB.Worksheets("Visual") With VisualWS .Range("L1:W1").Find(MonthName, , xlValues, xlWhole).Activate End With MonthCol = ActiveCell.Column MonthBefore = MonthCol - 1 End Sub 

我最初的回答是正确的。 有monthname = listofmonths.value这行是有问题的,因为编译器不知道什么是listofmonths。 然后剩下的要作为userform的属性使用userformname.property来解决,所以请调整这个,然后请澄清一下listofmonths是什么以及我们从哪里得到的。 没有问题线,现在应该编译。

 Option Explicit Sub initialize() 'The variables will keep their value on all the subs 'UserForm1.MonthName = Listofmonths.Value ' this is a issue since listofmonths is not defined Set UserForm1.MainWB = ThisWorkbook Set UserForm1.VacationWS = UserForm1.MainWB.Worksheets(1) Set UserForm1.HealingWS = UserForm1.MainWB.Worksheets(2) Set UserForm1.IllnessWS = UserForm1.MainWB.Worksheets(3) Set UserForm1.Lists = UserForm1.MainWB.Worksheets("Lists") Set UserForm1.VisualWS = UserForm1.MainWB.Worksheets("Visual") With UserForm1.VisualWS .Range("L1:W1").Find(UserForm1.MonthName, , xlValues, xlWhole).Activate End With UserForm1.MonthCol = ActiveCell.Column UserForm1.MonthBefore = UserForm1.MonthCol - 1 End Sub