我尝试运行sql时运行时错误类型不匹配

时间:2017-10-27 07:08:20

标签: excel vba

这是我的代码

Option Explicit
Dim niFlag As Integer

Private Sub OpenDB(ByRef cnn As ADODB.Connection)

cnn.ConnectionString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, 
*.xlsb)};DBQ=" & _


ActiveWorkbook.Path & Application.PathSeparator & ActiveWorkbook.name

cnn.Open

End Sub


Private Sub cmdPopul_Click()

Dim strSQL As String

Dim cnn As ADODB.Connection

Dim rs As ADODB.Recordset

niFlag = 1

strSQL = "Select Distinct [Group] From [Data$] Order by [Group]"

Set cnn = New ADODB.Connection

OpenDB cnn

cmbCompany.Clear

Set rs = New ADODB.Recordset

rs.Open strSQL, cnn, adOpenKeySet, adLockOptimistic

Set cnn = Nothing

If rs.RecordCount > 0 Then

Do While Not rs.EOF


**cmbCompany.AddItem rs.Fields(0)** 'the error is here


rs.MoveNext

Loop

Else

MsgBox "I was not able to find any unique Group.", vbCritical + vbOKOnly

Set rs = Nothing

Exit Sub

End If

End Sub

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

将您的代码更改为:

If rs.RecordCount > 0 Then

    Do While Not rs.EOF

        Debug.Print rs.Fields(1)
        Stop
        Debug.Print rs.Fields(0)
        Stop
        '**cmbCompany.AddItem rs.Fields(0)**    'the error is here
        rs.MoveNext
    Loop
Else

当代码停止时,查看您在即时窗口中获得的内容。然后进一步修改。如果您的值为Null,请尝试以下操作:

If not IsNull (rs.Fields(0)) then