Excel VBA。如何在组合框中设置默认值和值的颜色

时间:2017-06-27 08:05:31

标签: excel-vba vba excel

两个问题。

1)如何在组合框变量1中设置默认值curCombo,当用户创建该变量时,它将自动获得默认值1

2)如何设置值1显示绿色背景,值2显示黄色背景,值3显示红色背景。

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 代码在这里

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:-1)

在excel中选择组合框中第一项的简单方法:

ComboBox.ListIndex = 0