填充ComboBox时,Excel VBA对象所需的错误

时间:2017-09-07 13:38:11

标签: excel vba combobox dropdown

我收到以下错误 -

运行时错误'424':需要对象

以下是我收到错误消息的代码。出现错误的行已用****

突出显示
    Sub LoadDropdown_Click()

Dim cnt As ADODB.Connection
Dim rst As ADODB.Recordset
Dim stDB As String, stSQL As String
Dim xlCalc As XlCalculation
Dim vaData As Variant
Dim k As Long

Set cnt = New ADODB.Connection

cnt.connectionString = Module1.GetConnectionString
stSQL = "EXEC dbo.GetData"


With cnt
    .CursorLocation = adUseClient 'Necesary for creating disconnected recordset.
    .Open stConn 'Open connection.
     'Instantiate the Recordsetobject and execute the SQL-state.
    Set rst = .Execute(stSQL)
End With

With rst
    Set .ActiveConnection = Nothing 'Disconnect the recordset.
    k = .Fields.Count
     'Populate the array with the whole recordset.
    vaData = .GetRows
End With

 'Close the connection.
cnt.Close

 'Manipulate the Listbox's properties and show the form.
With ComboBox21
        .Clear       ' **** the error comes at this line since ComboBox21 is empty ******
        .BoundColumn = k
        .List = Application.Transpose(vaData)
        .ListIndex = -1

End With

Dim i As Integer

 'Release objects from memory.
Set rst = Nothing
Set cnt = Nothing


    End Sub

这些是我所知道的事情 -

  1. ComboBox实际上存在于Sheet1中,称为Priorities。 See this screenshot showing that Sheet1 contains a Combobox called ComboBox21

  2. 下面的函数LoadDropdown_Click出现在Sheet1中。 See this screenshot for details

  3. 从某些计算机运行时,此代码有效。它曾经在我的机器上工作,但现在我突然收到此错误而没有对代码或环境进行任何更改。

  4. 我尝试将ComboBox21更改为Sheet1.ComboBox21,但我收到了编译错误 - 找不到方法或数据成员。

  5. 如果有人可以提供帮助,那将会很棒!

2 个答案:

答案 0 :(得分:0)

请更改您的代码:

 With ComboBox21
            .Clear       ' **** the error comes at this line since ComboBox21 is empty ******
            .BoundColumn = k
            .List = Application.Transpose(vaData)
            .ListIndex = -1

    End With

'With the below:

     Sheet1.ComboBox21.Clear

With Sheet1.ComboBox21
        .BoundColumn = k
        .List = Application.Transpose(vaData)
        .ListIndex = -1
End With

答案 1 :(得分:0)

基本上,您只需添加“ On Error Resume Next”,以避免弹出这些烦人的错误消息,然后添加“ Err.Clear”以清除错误标志,以防万一。

Private Sub ComboBox1_Change()
     On Error Resume Next
     ComboBox5.List = Sheets("Data").Range("B1:B6").Value
     Err.Clear
End Sub

注意:这可能不是正确的处理方式,但至少对我有用