将列表框选择设置为变量

Set Listbox selection as variable

我想创建类似 "Patch" 的文件,我可以将其发送给用户,他们可以使用它来修补现有模板。

我想要做的是让用户表单带有一个列表框,显示所有当前打开的 Excel 文件,然后用户 select 他们想要修补的文件并单击一个按钮运行补丁脚本。

我对用户表单和整个 vba 非常陌生,并且在尝试将 'Listbox1.Selection' 设置为后续补丁代码可以引用的变量时遇到困难。我目前的 userform/listbox 代码如下(它只允许 selection of item:

Private Sub UserForm_Activate()

Dim wb As Workbook

For Each wb In Workbooks
    If Windows(wb.Name).Visible Then _
      ListBox1.AddItem wb.Name
Next

End Sub

一旦用户 select 文件,我该如何将其设置为变量?

向您的用户窗体添加命令按钮并添加以下代码:

Private Sub CommandButton1_Click()

ActiveSheet.Range("A1").Value = ListBox1.Text


End Sub

这会将选定的选项打印到 A1。您可以将其保存到变量中,以进一步保存。

基本上ListBox1.Text会给你选择的选项。

如何将其设置为变量?

Private Sub doPatch()
With Me.ListBox1
    Dim currIndex&
    currIndex = .ListIndex             ' assign zerobased index number to variable

    ' how do I go about setting that as a variable?
      Dim currWB
      currWB = .List(currIndex, 0)     ' get chosen list element in column zero based on current index

    ' 'or simply:
    ' currWB = .Value                  ' sufficient in your case as only one column listed

    ' display both variables in immediate window of your VB Editor
      Debug.Print "zerobased Listindex#: " & currIndex & " ~> " & currWB

    ' do patch stuff...

End With
End Sub

最终您可以通过双击命令按钮 and/or 来调用上述过程,例如通过

Private Sub CommandButton1_Click()
    doPatch
End Sub

Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
    doPatch
End Sub