简体   繁体   English

组合框VB​​A Excel

[英]Combo box VBA Excel

I am using around 8-10 comboboxes(form control),each one having the same list of items populated. 我正在使用大约8-10个组合框(窗体控件),每个组合框都填充了相同的项目列表。 Based on the user's selection from the dropdown, a certain value is displayed in a different cell. 根据用户从下拉菜单中的选择,某个值将显示在其他单元格中。 I wanted to know if there is way to do this without using a loop(for dropdowns) as all have the same function. 我想知道是否有办法不使用循环(对于下拉菜单),因为它们都具有相同的功能。 Here is the code I am using: 这是我正在使用的代码:

Dim ws As Sheets
Set ws = ThisWorkbook.Sheets(Array("S1 Fuel Consumption", "EF_Stat", "Summary"))
Dim i As Integer


For i = 1 To 8
With ws(1).Shapes("Fuel " & i).ControlFormat    ~~> 'This is the loop I'm talking about(for 8 shapes)

Select Case .ListIndex

Case 1
ws(3).Range("B" & i).Value = Empty
Case 2
ws(3).Range("B" & i).Value = ws(2).Range("B4").Value
Case 3
ws(3).Range("B" & i).Value = ws(2).Range("C4").Value
Case 4
ws(3).Range("B" & i).Value = ws(2).Range("D4").Value

End Select
End With
Next i

Assign the same macro to all of the comboboxes and use: 将相同的宏分配给所有组合框并使用:

With WS(1).Dropdowns(Application.Caller)

to get a reference to the combobox that triggered the macro. 获取对触发宏的组合框的引用。

If you need to figure out the 'i' value you were using in the loop originally, you can do something like this: 如果您需要弄清楚原来在循环中使用的'i'值,则可以执行以下操作:

Dim ws As Sheets
Dim sCaller As String
Dim i As Integer
Dim rgOutput As Range

Set ws = ThisWorkbook.Sheets(Array("S1 Fuel Consumption", "EF_Stat", "Summary"))

sCaller = Application.Caller

Set rgOutput = ws(3).Range("B" & Replace(sCaller, "Fuel ", ""))

Select Case ws(1).DropDowns(sCaller).ListIndex

    Case 1
        rgOutput.Value = vbNullString
    Case 2
        rgOutput.Value = ws(2).Range("B4").Value
    Case 3
        rgOutput.Value = ws(2).Range("C4").Value
    Case 4
        rgOutput.Value = ws(2).Range("D4").Value

End Select

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM