从用户表单button传递string单击以Excel VBA
我创build了一个用户窗体,其中包含打开的PowerPoint文件的列表,并让用户select要使用哪一个。 当他们点击“设置PowerPoint”button时,我想将该button传递给VBA模块,在那里我将PowerPoint设置为用户刚刚select的那个。 任何帮助将不胜感激。
UserForm代码:
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
这就是UserForm的样子:
那我怎样才能拿SelectedPPT并把它传递给模块,这样我才能select那个特定的PowerPoint?
您SelectedPPT
是破解封装 ,可以从表单外部设置,而不仅仅是表单的代码。 您可以通过将该字段设置为Private
并为其公开一个Property Get
过程来缓解此devise问题:
Option Explicit Private SelectedPPT As String Public Property Get SelectedFile() As String SelectedFile = SelectedPPT End Property
在窗体的Initialize
或Activate
处理程序中设置ComboBox
行源,所以它被初始化一次。 然后在ComboBox中的select更改时分配SelectedPPT
– 这是您的ComboBox1_Change
处理程序。
这消除了对[设置PowerPoint]button及其Click
处理程序的需求。
我会有一个[确定]和[取消]button,我会让表单记住是否取消:
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
然后还需要考虑用户单击红色Xbuttonclosures表单的情况; 你可以通过处理窗体的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
- 创build和销毁表单对象是调用者的责任
- 调用者每次都使用表单的一个
New
实例 - 调用者具有对表单通过属性公开的任何值的只读访问权限