Excel VBA. How to set default value in a combo box

2019-09-11 15:52发布

two questions.

1) How to set a default value 1 in the combo box variable curCombo, that when user creates that, it will automatically get a default value 1.

2) How to set that a value 1 shows green background, a value 2 shows yellow background and the value 3 shows red background.

Sub ComboBox()

Dim curCombo As Object
Dim ws As Worksheet
Dim rng As Range

Set ws = ActiveSheet

With ws

    Set rng = .Cells.Item(ActiveCell.row, 3)


    Set curCombo = .Shapes.AddFormControl(xlDropDown, _
                                          Left:=rng.Left, _
                                          Top:=rng.Top, _
                                          Width:=rng.Width, _
                                          Height:=rng.Height)

    With curCombo
        .ControlFormat.DropDownLines = 3

        .ControlFormat.AddItem "1", 1
        .ControlFormat.AddItem "2", 2
        .ControlFormat.AddItem "3", 3
        .Name = "myCombo" 

    End With



End With

End Sub code here

2条回答
神经病院院长
2楼-- · 2019-09-11 16:33
Sub ComboBox()

Dim curCombo As Object
Dim ws As Worksheet
Dim rng As Range

Set ws = ActiveSheet

With ws

    Set rng = .Cells.Item(ActiveCell.Row, 3)


    Set curCombo = .Shapes.AddFormControl(xlDropDown, _
                                          Left:=rng.Left, _
                                          Top:=rng.Top, _
                                          Width:=rng.Width, _
                                          Height:=rng.Height)

    With curCombo
        .ControlFormat.DropDownLines = 3

        .ControlFormat.AddItem "1", 1
        .ControlFormat.AddItem "2", 2
        .ControlFormat.AddItem "3", 3
        **.ControlFormat.ListIndex = 1**
        .Name = "myCombo"
    End With


End With



End Sub
查看更多
一纸荒年 Trace。
3楼-- · 2019-09-11 16:33

The simple way og selecting the first item in a combobox in excel:

ComboBox.ListIndex = 0

查看更多
登录 后发表回答