I have created a UserForm that takes a list of open PowerPoint files and lets a user select which one they want to use. When they click the 'Set PowerPoint' button, I want to pass that button to a VBA Module where I will set the PowerPoint to the one the user just selected. Any help would be greatly appreciated.
UserForm Code:
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
This is what the UserForm looks like:
Then how can I take SelectedPPT and pass it to the module so I can select that specific PowerPoint?
Your SelectedPPT
is breaking encapsulation and can be set from outside the form, not just the form's code. You can mitigate this design issue by making the field Private
and exposing a Property Get
procedure for it:
Option Explicit
Private SelectedPPT As String
Public Property Get SelectedFile() As String
SelectedFile = SelectedPPT
End Property
Set the ComboBox
row source in the form's Initialize
or Activate
handler, so it's initialized once. Then assign SelectedPPT
when the selection changes in the ComboBox - that's your ComboBox1_Change
handler.
That removes the need for that [Set PowerPoint] button and its Click
handler.
I would have an [Ok] and a [Cancel] button, and I'd make the form remember whether it's cancelled:
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
And then you also need to account for the case where the user clicks the red X button to close the form; you can do that by handling the forms' QueryClose
event:
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
The rest of the logic belongs to the calling code - let's say the form is called MyAwesomeForm
; you'd have something like this:
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
Note:
Unload Me
New
instance of the form every time
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.