所以这是我的目标:我需要在多选ListBox上执行不同的宏。我是vba的入门者,目前有些任务对我来说有些困难。 有一个带有9个选项的多选ListBox。如果选择选项“Exfoliación”,它将执行名为“ macro4”的宏。这是完全可自定义的,因此,如果我从列表框中选择选项“Exfoliación”和“ Estanqueidad”,它将执行宏4和3(与它们相关的宏)。
我已经看过Internet上的一些示例,但是它们与ListBox处理列,表格等有关。但是,使用宏的解释并不多。
用户选择选项,然后在工作表中按一个名为“ Botón
”的“提交”按钮。列表框中的选项标记为vector(i)=1
。通过for循环,将读取选项,并使用包含这些宏名称的数组a(i)
执行与这些选项相对应的宏。
Sub Submit()
'Getting selected items in ListBox1
Dim vector(1 To 11) As Integer
Dim i As Integer
Dim a(1 To 9) As String
'Private Sub CommandButton1_Click()
For i = LBound(a) To UBound(a)
vector(i) = 0
Next i
With Sheets("Botón").ListBox1
Select Case (ListBox1.Text)
Case "Tornillo Resorte": vector(1) = 1
Case "Categoría Manguito": vector(2) = 1
Case "Estanqueidad": vector(3) = 1
Case "Exfoliación": vector(4) = 1
Case "Material vaina": vector(5) = 1
Case "Diseño EC": vector(6) = 1
Case "Curva Q vs Enriquecimiento": vector(7) = 1
Case "Curva Criticidad": vector(8) = 1
Case "Curva de carga t. enfriamiento": vector(9) = 1
Case "Condicioón de transporte": vector(10) = 1
Case "ATI": vector(11) = 1
Case ""
MsgBox "nothing selected"
Case Else
MsgBox Me.ListBox1.Text
End Select
Dim MN As String
For i = 1 To N 'Fill the array
a(i) = "macro" & i
Next
MN = "Módulo5" 'Module where i have the worksheet I'm working with
Dim N As Integer
N = 11
For i = LBound(a) To UBound(a)
If vector(i) = 1 Then
Application.Run MN & "." & a(i)
End If
Next i
End Sub
我发现Select Case (ListBox1.Text)
语句有麻烦。
它不会编译,也不知道如何使用Select Case调用listBox。
预先感谢您的帮助:)
编辑:带有新代码。选择方法:
`Private Sub Command Button1_Click() 'This is a button that opens the multilist with the different options. It works correctly
Worksheets("Botón").ListBox1.Clear
ListBox1.Height=200
ListBox1.Width=250
Dim mylist As Variant
mylist=Array("Tornillo Resorte",...,"Condicioón de transporte")
ListBox1.List=mylist
End Sub
Sub Submit() ''here's the macro with the button assigned to execute the selection. This is where I get the problem.
With Sheets("Botón").ListBox1
MN = "Módulo5" 'Module where i have the worksheet I'm working with
For X = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(X) = True Then
Application.Run MN & "." & .ListIndex + 1
Else
MsgBox "No se ha seleccionado ningún filtro"
End If
Next X
End With
End Sub
答案 0 :(得分:0)
如果您只想选择一个宏-并假设这些宏被依次命名为macro1到macrox,那么您可以这样做:
Sub Submit()
With Sheets("Botón").ListBox1
if .listindex = -1 then
MsgBox "nothing selected"
Else
MN = "Módulo5" 'Module where i have the worksheet I'm working with
Application.Run MN & "." & .listindex +1
End If
End With
End Sub
如果要执行多个操作,则需要循环遍历.selected数组,依次调用宏