具有精选列表的ActiveX组合框

时间:2019-07-18 14:04:16

标签: excel vba combobox activex

我在看这个问题:How to create and populate ActiveX combo box

我想知道,当项目列表来自某个范围时如何实现,以及如何指定该列表应放置在哪个单元格中。

此外,最好有两个不同的工作表中的值范围。

@Component({
  selector: 'expansion-overview-example',
  animations: [
    trigger('openClose', [
      // ...
      state('open', style({
        transform: 'rotate(0deg)'
      })),
      state('closed', style({
        transform: 'rotate(-180deg)'
      })),
      transition('open => closed', [
        animate('1s')
      ]),
      transition('closed => open', [
        animate('1s')
      ]),
    ]),
  ],
  templateUrl: 'expansion-overview-example.html',
  styleUrls: ['expansion-overview-example.css'],
})
export class ExpansionOverviewExample {
  panelOpenState = false;
}

1 个答案:

答案 0 :(得分:1)

我稍微调整了一下代码以进行清理。避免使用ActiveSheet,而是使用对您感兴趣的工作表的显式引用。另外,您还应该将对象存储到变量中:

Option Explicit

Sub CreateComboBox1()

Dim sht As Worksheet
Dim cb As ComboBox
Dim sourceRange As Range
Set sht = ThisWorkbook.Worksheets("Name of your worksheet")
Set sourceRange = sht.Range("A1:A10") 'example source range

Set cb = sht.OLEObjects.Add(ClassType:="Forms.ComboBox.1", Link:=False, DisplayAsIcon:=False, Left:=50, Top:=80, Width:=100, Height:=15).Object
cb.List = sourceRange.Value

End Sub

基本上,您可以使用.List属性来指定来源范围。

另一种实现方法是使用For-Each循环,循环浏览要添加到列表中的项目。这样,您可以将来自不同工作表的两个不同范围的项目添加到列表中:

Option Explicit

Sub CreateComboBox1()
Dim cell As Range
Dim sht1 As Worksheet
Dim sht2 As Worksheet
Dim cb As ComboBox
Dim sourceRange1 As Range
Dim sourceRange2 As Range

Set sht1 = ThisWorkbook.Worksheets("Name of your worksheet 1")
Set sht2 = ThisWorkbook.Worksheets("Name of your worksheet 2")
Set sourceRange1 = sht1.Range("A1:A10")
Set sourceRange2 = sht2.Range("A1:A10")

Set cb = sht1.OLEObjects.Add(ClassType:="Forms.ComboBox.1", Link:=False, DisplayAsIcon:=False, Left:=50, Top:=80, Width:=100, Height:=15).Object

For Each cell In sourceRange1
    cb.AddItem cell.Value
Next cell
For Each cell In sourceRange2
    cb.AddItem cell.Value
Next cell

End Sub