【发布时间】:2019-07-01 18:19:57
【问题描述】:
所以这是我的目标:我需要根据多选 ListBox 执行不同的宏。我是 vba 的初学者,目前有些任务对我来说有点困难。 有一个带有 9 个选项的多项选择列表框。如果您选择“Exfoliación”选项,它会执行名为“macro4”的宏。这是完全可定制的,所以如果我从 ListBox 中选择“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
【问题讨论】:
-
不是 listbox.value 而不是 listbox.text 吗?我在努力回忆。或者 Me.ListBox.List(y) 其中 y 是列表框中的索引号。我似乎认为我过去通过循环访问列表项来做到这一点,例如对于 y = 0 到 me.listbox.listcount - 1
-
它会给你什么错误?此外,
With Sheets("Botón").ListBox1之前的行没有匹配的End With。而你没有对 With 语句做任何事情。 -
erazov4 抱歉,刚刚编辑此论坛的代码并删除了 End With 声明。你是对的,在这种情况下不需要 with 。我将其更改为
Select Case (Worksheets("Botón").ListBox1.Text),现在我遇到的问题是每次执行它时,即使我选择了一些选项,我也会收到“未选择任何内容”的消息。 -
Application.Run MN & ".macro" & .ListIndex + 1
-
另外 - 你在每个元素上都给出“没有选择”messaqe,除了一个被选中的元素。