【问题标题】:Passing a variable from class module to userform将变量从类模块传递到用户窗体
【发布时间】:2021-11-18 09:53:16
【问题描述】:

嘿嘿, 我正在尝试设计一个代码,其中许多命令按钮调用相同的用户窗体。我已经创建了类模块并让它工作,以便它们都调用用户窗体,但我需要从类模块传递到用户窗体初始化的按钮的名称。我已经尝试使用属性获取和公共功能,但无法使其正常工作。我要传递的变量是“ScreenShotCap”作为字符串任何人,谁能帮忙?

类模块代码

Option Explicit

Public ScreenShotCap As String
Public WithEvents CmdBtn As MSForms.CommandButton


Property Set obj(btns As MSForms.CommandButton)

'Defines the property of the object called
    Set CmdBtn = btns
    
End Property


Private Sub CmdBtn_Click()

'Gets the button caption
    ScreenShotCap = CmdBtn.Name

'Loads the userform
    ufScreenshot.Show
  
End Sub

用户表单代码

Private Sub UserForm_Initialize()

Dim btnNo As Variant
Dim imNo1, imNo2, imNo3 As Integer


'Gets the number of the button
    btnNo = Right(ScreenShotCap, 1)

'Sets the image number
    imNo1 = Int(btnNo + 2)
    imNo2 = Int(btnNo + 3)
    imNo3 = Int(btnNo + 4)
    
'Loads the image from MSForms into userform
    If ScreenShotCap = Worksheets("SW_TEST").OLEObjects("CommandButton1").Name Then
        Application.ScreenUpdating = False
            Me.Image1.Picture = Worksheets("SW_TEST").OLEObjects("Image1").Object.Picture
            Me.Image2.Picture = Worksheets("SW_TEST").OLEObjects("Image2").Object.Picture
            Me.Image3.Picture = Worksheets("SW_TEST").OLEObjects("Image3").Object.Picture
        Application.ScreenUpdating = True
    Else
        Application.ScreenUpdating = False
            Me.Image1.Picture = Worksheets("SW_TEST").OLEObjects("Image" & imNo1).Object.Picture
            Me.Image2.Picture = Worksheets("SW_TEST").OLEObjects("Image" & imNo2).Object.Picture
            Me.Image3.Picture = Worksheets("SW_TEST").OLEObjects("Image" & imNo3).Object.Picture
            
        'after any change vba has to be told to refresh the UserForm for the change to appear
            Me.Repaint
        Application.ScreenUpdating = True
    End If
  
End Sub

【问题讨论】:

  • 给表单添加隐藏标签并设置表单打开后的值

标签: vba pass-by-reference userform pass-by-value first-class-modules


【解决方案1】:

UserForm_Initialize() 中的代码移动到带有参数的新子中或将其重命名为:

Public Sub LoadButtonImage(ScreenShotCap As String)

然后在您的CmdBtn_Click() 子中:

Load ufScreenshot.Show
ufScreenshot.LoadButtonImage CmdBtn.Name 
uScreenshot.Show

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-04
    • 2016-03-25
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    相关资源
    最近更新 更多