查询Excel工作表,查看rs是否为空

时间:2018-02-27 14:16:50

标签: excel-vba adodb vba excel

我在下面编写了proc,它工作正常,但我想检查记录集是否为空。但是,rs.EoFrs.BoF始终返回False,即使没有数据也是如此。使这项工作的诀窍是什么?

Sub PrepData()
    Dim ws As Worksheet, wb As Workbook
    Dim cn As New ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim rs2 As ADODB.Recordset
    Dim strSql As String, recs As Long

    Set wb = ActiveWorkbook
    Set ws = ActiveSheet

    'create connection
    With cn
        .Provider = "Microsoft.ACE.OLEDB.12.0"
        .ConnectionString = "Data Source=" & wb.FullName & ";" & _
        "Extended Properties=""Excel 12.0;HDR=YES"";"
        .Open
    End With

    'check trades without matching couterparty
    strSql = "select distinct tf.counterPart from [TradeFile$A3:G5000] tf " & _
             "left join [CounterpartiesMapping$] c on tf.counterpart = c.counterpart " & _
             "where c.investee is null"
    Set rs = cn.Execute(strSql, recs)

    'HERE I'd like to see if the recordset is empty,
    'but rs.eof and rs.bof are always FALSE regardless of the result
    Debug.Print rs.BOF, rs.EOF, rs.RecordCount
    ws.Range("p3").CopyFromRecordset rs
    rs.Close

    cn.Close
End Sub

2 个答案:

答案 0 :(得分:0)

您是否尝试使用记录集的RecordCount属性来查找返回的行数?

 Debug.Print rs.RecordCount

答案 1 :(得分:0)

我终于找到了解决方案here
只需替换

Set rs = cn.Execute(strSql, recs)

通过

Set rs = New ADODB.Connection
rs.CursorLocation = adUseCLient
rs.Open strSql, cn

现在Debug.Print rs.BOF, rs.EOF, rs.RecordCount按预期工作了!