无法填充我的OLEObject组合框

时间:2014-12-24 20:13:59

标签: vba excel-vba access-vba excel

我正在尝试使用来自访问数据库的数据通过adodb连接和记录集填充我的组合框。代码以前运行正常,但在正常的用户窗体中,我的问题是我无法正确引用combobox.additem属性。

当ActiveX对象直接在工作表“Mainwindow”上时,如何引用它? 形状的代号是:CombBox_Instruments 控制代码名称应为:Forms.ComboBox.1

我有市场我收到错误,当前错误是:运行时错误1004:应用程序定义或对象定义错误

这是我的代码

Private Sub Workbook_Open()

  Dim DataConnection As ADODB.Connection: Set DataConnection = New ADODB.Connection
  Dim RecordSet As ADODB.RecordSet: Set RecordSet = New ADODB.RecordSet

  Dim SQLString As String
  Const ConnectionPath As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\name\Desktop\Database.accdb;Persist Security Info=False;"

  DataConnection.ConnectionString = ConnectionPath
  DataConnection.Open

  SQLString = "SELECT Name FROM MSysObjects WHERE Type =1 AND Flags=0"

  With RecordSet
    .ActiveConnection = DataConnection
    .Source = SQLString
    .LockType = adLockReadOnly
    .CursorType = adOpenForwardOnly
    .Open
    End With

Do Until RecordSet.EOF = True
    If RecordSet.Fields(0) <> "Instruments" Then
        Debug.Print RecordSet.Fields(0)
        Sheets("Mainwindow").OLEObjects("Forms.ComboBox.1").AddItem RecordSet.Fields(0) - ISSUE IS HERE!
        RecordSet.MoveNext
    Else
        RecordSet.MoveNext
    End If
    Loop

End Sub

1 个答案:

答案 0 :(得分:1)

假设名为CombBox_Instruments的组合框位于“Mainwindow”表单上,您的代码应为:

Sheets("Mainwindow").CombBox_Instruments.AddItem RecordSet.Fields(0)