【问题标题】:Pass a string from a User Form Button Click to Excel VBA从用户表单按钮传递一个字符串单击到 Excel VBA
【发布时间】:2017-05-04 03:05:23
【问题描述】:

我创建了一个用户窗体,它包含一个打开的 PowerPoint 文件的列表,并让用户选择他们想要使用的文件。当他们单击“设置 PowerPoint”按钮时,我想将该按钮传递给 VBA 模块,在该模块中我会将 PowerPoint 设置为用户刚刚选择的那个。任何帮助将不胜感激。

用户窗体代码:

Option Explicit

Public SelectedPPT As String

Private Sub cmdCloseForm_Click()
    Unload Me
End Sub

Private Sub ComboBox1_Change()
    ComboBox1.RowSource = "Array"
End Sub

Private Sub setPPT_Click()
    'Not sure if this is the best way to select the ppt the user has chosen?
    SelectedPPT = Me.ComboBox1.Value
End Sub

这是用户窗体的样子:

那么我如何获取 SelectedPPT 并将其传递给模块,以便我可以选择特定的 PowerPoint?

【问题讨论】:

  • function PassPPT(strSelectedPPT as string)......end function 使用 PassPPT(me.combobox1.value)

标签: vba excel userform


【解决方案1】:

您的SelectedPPT 打破了封装,可以从表单外部进行设置,而不仅仅是表单的代码。您可以通过创建字段Private 并为其公开Property Get 过程来缓解此设计问题:

Option Explicit
Private SelectedPPT As String

Public Property Get SelectedFile() As String
    SelectedFile = SelectedPPT
End Property

在表单的Initialize 或Activate 处理程序中设置ComboBox 行源,因此它被初始化一次。然后在 ComboBox 中的选择更改时分配 SelectedPPT - 那是您的 ComboBox1_Change 处理程序。

这消除了对 [设置 PowerPoint] 按钮及其Click 处理程序的需要。

我会有一个 [Ok] 和一个 [Cancel] 按钮,我会让表单记住它是否被取消:

Private IsCancelled As Boolean

Public Property Get Cancelled() As Boolean
    Cancelled = IsCancelled
End Property

Private Sub OkButton_Click()
    Me.Hide
End Sub

Private Sub CancelButton_Click()
    IsCancelled = True
    Me.Hide
End Sub

然后你还需要考虑用户点击红色X按钮关闭表单的情况;您可以通过处理表单的QueryClose 事件来做到这一点:

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = VbQueryClose.vbFormControlMenu Then
        IsCancelled = True
        Cancel = True
        Me.Hide
    End If
End Sub

其余的逻辑属于调用代码——假设表单名为MyAwesomeForm;你会有这样的东西:

Dim filename As String
With New MyAwesomeForm
    .Show
    If Not .Cancelled Then
        filename = .SelectedFile
        'do whatever you wanted to do with that filename
    End If
End With

注意:

  • 表单绝不会调用Unload Me
  • 创建和销毁表单对象是调用者的责任
  • 调用者每次都使用New 表单实例
  • 调用者对表单通过属性公开的任何值具有只读访问权限

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-25
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多