使用VBA CommandButton值从Userform到模块的变量

时间:2017-11-23 06:33:10

标签: excel vba excel-vba userform

我知道如果我们将一个变量命名为Public,那么如果变量在sub之间传递End Sub,则变量可以保持其值。但我的承诺是我有一个变量,它在userform中从commandnbutton获取其值,每次我尝试将此变量设置为userform sub时,我都会收到编译错误。我有一个月份列表框,在选择月份后按下命令按钮,宏开始。我知道变量的值会在H传递Ens Sub之间移动,我需要在其他子传递中使用这个变量值,我需要它是动态的,任何人都知道什么可以帮助我? / p>

这是userform sub:

 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

1 个答案:

答案 0 :(得分:1)

我的初步答案是正确的。有monthname = listofmonths.value的行是有问题的,因为编译器不知道listofmonth是什么。然后必须使用 userformname.property 将其余部分作为userform的属性进行处理,因此请对此进行调整,然后请说明listofmonth是什么以及我们从哪里获得。没有问题,它现在应该编译。

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