将列表框选择设置为变量

时间:2019-06-24 06:03:12

标签: excel vba listbox userform

我想创建一个类似“补丁”文件的东西,我可以将其发送给用户,他们可以使用它来补丁其现有模板。

我要做的是拥有一个带有显示所有当前打开的Excel文件的列表框的用户窗体,然后用户选择要修补的文件并单击按钮以运行修补脚本。

对于用户窗体和整个vba来说是非常新的知识,很难将“ Listbox1.Selection”设置为后续补丁代码可以引用的变量。我目前在userform / listbox中的代码如下(它只允许选择项目:

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

用户选择文件后,如何将其设置为变量?

2 个答案:

答案 0 :(得分:1)

在用户窗体中添加一个命令按钮,并添加以下代码:

Private Sub CommandButton1_Click()

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


End Sub

这会将“已选择”选项打印到A1。您可以将其保存到变量中,以便进一步扩展。

基本上ListBox1.Text将为您提供选定的选项。

答案 1 :(得分:1)

如何将其设置为变量?

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

最终,您可以通过命令按钮和/或双击(例如)来调用上述过程。通过

Private Sub CommandButton1_Click()
    doPatch
End Sub

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