2017-05-03 43 views
0

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

用户窗体代码:

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 

这是窗体的样子: enter image description here

那我该怎么走SelectedPPT并把它传递到模块,所以我可以选择特定的PowerPoint?

+2

'功能PassPPT(strSelectedPPT作为字符串)......结束功能'使用像'PassPPT(me.combobox1.value)' –

回答

1

您的SelectedPPT正在打破封装并且可以从表单外部设置,而不仅仅是表单的代码。您可以通过现场Private和暴露Property Get程序为它减轻这一设计问题:

Option Explicit 
Private SelectedPPT As String 

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

设置在窗体的InitializeActivate处理程序ComboBox行源,所以它的初始化一次。然后在ComboBox中选择更改时指定SelectedPPT - 这是您的ComboBox1_Change处理程序。

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

我将有一个[确定]和[取消]按钮,我会做的形式记住无论是取消:

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实例
  • 调用者具有对任何值的只读访问权限for通过属性公开
+0

非常感谢,这工作奇迹! – BH57

+0

@ BH57乐意帮忙!我希望更多的VBA开发者意识到用户表单有一个默认实例,以及针对该默认实例的有效和反OOP工作方式。确保你看看我的[Rubberduck](http://www.rubberduckvba.com/)项目,如果你认真对待VBA =) –