为什么我的vba编码输出是这样的?

时间:2017-06-22 01:33:59

标签: vba excel-vba excel

这是我的编码,我想从我在Excel中的另一个工作表创建的数据库中构建一个更新下拉列表,但错误会让我的编码分散注意力,我想如何解决它?

  

Microsoft ODBC Excel Driver; Too few parameters. Expected 1.

     

Microsoft ODBC Excel驱动程序;参数太少。预期1。

此指令发生错误:

rs.Open strSQL, Cnn, adOpenKeyset, adLockOptimistic

这是周围的代码:

Option Explicit 
Public Cnn As New ADODB.Connection 
Public Rs As New ADODB.Recordset 
Public StrSQL As String 

Public Sub OpenDB() 
    If Cnn.State = adStateOpen Then Cnn.Close 
    Cnn.ConnectionString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & _ 
    ActiveWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name 
Cnn.Open 
End Sub 

Public Sub CloseRS() 
    If Rs.State = adStateOpen Then Rs.Close 
    Rs.CursorLocation = adUseClient 
End Sub

Private Sub CommandButton4_Click()
strSQL = "Select Distinct [Equipment] From [mechanical$] Order by [Equipment]"
    CloseRS
    OpenDB
    ComboBox1.Clear

    rs.Open strSQL, Cnn, adOpenKeyset, adLockOptimistic '<<< ERROR HERE
    If rs.RecordCount > 0 Then
        Do While Not rs.EOF
            ComboBox1.AddItem rs.Fields(0)
            rs.MoveNext
        Loop
    Else
        MsgBox "I was not able to find any unique Products.", vbCritical + vbOKOnly
        Exit Function
    End If

    '----------------------------
    strSQL = "Select Distinct [SWEC] From [mechanical$] Order by [SWEC]"
    CloseRS
    OpenDB
    ComboBox2.Clear

    rs.Open strSQL, Cnn, adOpenKeyset, adLockOptimistic
    If rs.RecordCount > 0 Then
        Do While Not rs.EOF
            ComboBox2.AddItem rs.Fields(0)
            rs.MoveNext
        Loop
    Else
        MsgBox "I was not able to find any unique Region(s).", vbCritical + vbOKOnly
        Exit Function
    End If
    '----------------------
    strSQL = "Select Distinct [Principal Name] From [mechanical$] Order by [Principal Name]"
    CloseRS
    OpenDB
    ComboBox3.Clear

    rs.Open strSQL, Cnn, adOpenKeyset, adLockOptimistic
    If rs.RecordCount > 0 Then
        Do While Not rs.EOF
            ComboBox3.AddItem rs.Fields(0)
            rs.MoveNext
        Loop
    Else
        MsgBox "I was not able to find any unique Customer Type(s).", vbCritical + vbOKOnly
        Exit Function
    End If
End Function
  

这是我的输出页面search form   我的数据库databse

1 个答案:

答案 0 :(得分:0)

我认为代码会像。

Option Explicit
Public Cnn As New ADODB.Connection
Public Rs As New ADODB.Recordset
Public StrSQL As String

Public Sub OpenDB()
    If Cnn.State = adStateOpen Then Cnn.Close
    Cnn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
            "Data Source=" & ThisWorkbook.FullName & ";" & _
            "Extended Properties=Excel 12.0;"

Cnn.Open
End Sub

Public Sub CloseRS()
    If Rs.State = adStateOpen Then Rs.Close
    Rs.CursorLocation = adUseClient
End Sub