使用VBA创建ComboBox列表,更新代码中指定的单元格值

时间:2016-09-07 13:11:30

标签: excel vba combobox

我要做的是创建一个程序,添加一些选项的组合框。然后,这些选项应根据所选的选项更改我在代码中指定的某些单元格中的某些值。

这就是我制作组合列表的方式:

Private Sub Workbook_Open()

With Worksheets("Sheet1").Columns("E")
 .ColumnWidth = 25
End With

For i = 1 To 6
    Set curCombo = Sheet1.Shapes.AddFormControl(xlDropDown, Left:=Cells(i, 5).Left, Top:=Cells(i, 5).Top, Width:=100, Height:=15)
    With curCombo
        .ControlFormat.DropDownLines = 3
        .ControlFormat.AddItem "Completed", 1
        .ControlFormat.AddItem "In Progress", 2
        .ControlFormat.AddItem "To be done", 3
        .Name = "myCombo" & CStr(i)
        .OnAction = "myCombo_Change"
    End With
Next i

End Sub

我希望每个下拉值触发事件myCombo_Change,然后只需更改单元格“D”例如,组合框3位于E3,我想要“完成”以清除单元格D3和完成以简单地将日期(和时间)存储到单元格D3。应该对E列中的所有组合框执行此操作。

Private Sub myCombo_Change(index As Integer)

Me.Range("D" & CStr(index)) = Me.myCombo.Value

End Sub

这是我开始考虑的代码,但我不知道如何使用整数作为索引参数NOR来调用事件如何使用所述索引访问单元格。

我想要的效果就是这样:

enter image description here

1 个答案:

答案 0 :(得分:2)

使用Application.Caller获取调用myCombo_Change事件的控件的名称。

Sub myCombo_Change()

    Dim curCombo As Shape
    Set curCombo = ActiveSheet.Shapes(Application.Caller)
    curCombo.TopLeftCell.Offset(0, -1) = Now

End Sub

将myCombo_Change分配给所有现有的DropDown:

Sub AssignMacroToAllListBoxes()
    Dim sh As Shape
    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        For Each sh In ws.Shapes
            If TypeName(sh.OLEFormat.Object) = "DropDown" Then
                sh.OLEFormat.Object.OnAction = "myCombo_Change"
            End If
        Next
    Next
End Sub

删除Sheet1上的所有DropDowns

Sub DeleteAllDropDownsOnSheet()
    For Each sh In Sheet1.Shapes
        If TypeName(sh.OLEFormat.Object) = "DropDown" Then
            sh.Delete
        End If
    Next
End Sub