在Excel中创建组合框以进行过滤

时间:2014-10-17 11:50:56

标签: excel-vba vba excel

stackoverflow中的新功能。我在工作中使用VBA,我在完成任务时遇到问题。我想创建一个在Excel工作表中创建一个组合框的宏,然后找到用户选择的单元格,并将该列的数据提供给组合框。如果我使用2个宏(1.创建梳子2.提供数据)工作正常。如果我试图将它们联合起来就行不通。找不到组合框。 问题是行:Sheet1.ComboBox1.AddItem Value 这是我的代码。感谢您提供的任何帮助

Global mycellCl As String
Sub CreateComboBox1()
'first part
Lastrow = Sheet1.Range("A" & Rows.Count).End(xlUp).Row

With ActiveSheet.OLEObjects.Add(ClassType:="Forms.ComboBox.1", _
                Link:=False, DisplayAsIcon:=False, Left:=250, Top:=10, Width:=100, _
                Height:=20)
End With
myvalue = ""
'end sub
'2nd part works fine as 2nd macro FeedData()
Dim Lrow As Long, test As New Collection
Dim Value As Variant, temp() As Variant
ReDim temp(0)

mycellCl = Mid(Application.ActiveCell.Address, 2, 1)
'Lastrow = Sheet1.Range("A" & Rows.Count).End(xlUp).Row

On Error Resume Next
temp = Sheet1.Range(mycellCl & "2:" & mycellCl & Lastrow).Value
For Each Value In temp
    If Len(Value) > 0 Then test.Add Value, CStr(Value)
Next Value
If Sheet1.Shapes.Count > 0 Then
For Each Value In test
    Sheet1.ComboBox1.AddItem Value
Next Value
End If
On Error GoTo 0
Set test = Nothing
End Sub

1 个答案:

答案 0 :(得分:0)

您不能将组合框称为Sheet1类的成员,因为它在编译时不存在。简单的解决方案是存储对您添加的组合框的引用并使用该变量:

Sub CreateComboBox1()
    Dim cbo                   As Object
    'first part
    Lastrow = Sheet1.Range("A" & Rows.Count).End(xlUp).Row

    Set cbo = ActiveSheet.OLEObjects.Add(ClassType:="Forms.ComboBox.1", _
                                         Link:=False, DisplayAsIcon:=False, Left:=250, Top:=10, Width:=100, _
                                         Height:=20).Object
    myvalue = ""
    'end sub
    '2nd part works fine as 2nd macro FeedData()
    Dim Lrow As Long, test    As New Collection
    Dim Value As Variant, temp() As Variant
    ReDim temp(0)

    mycellCl = Mid(Application.ActiveCell.Address, 2, 1)
    'Lastrow = Sheet1.Range("A" & Rows.Count).End(xlUp).Row

    On Error Resume Next
    temp = Sheet1.Range(mycellCl & "2:" & mycellCl & Lastrow).Value
    For Each Value In temp
        If Len(Value) > 0 Then test.Add Value, CStr(Value)
    Next Value
    If Sheet1.Shapes.Count > 0 Then
        For Each Value In test
            cbo.AddItem Value
        Next Value
    End If
    On Error GoTo 0
    Set test = Nothing
End Sub