查询Excelsheet,判断rs是否为空
Querying Excel sheet, find out if rs is empty
我写了下面的过程,它工作正常,除了我想检查记录集是否为空。但是,rs.EoF
和rs.BoF
总是returnFalse
,即使没有数据。完成这项工作的诀窍是什么?
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
您是否尝试过使用 RecordCount 属性 记录集来查找返回的行数?
Debug.Print rs.RecordCount
我终于找到了解决办法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
按预期工作!
我写了下面的过程,它工作正常,除了我想检查记录集是否为空。但是,rs.EoF
和rs.BoF
总是returnFalse
,即使没有数据。完成这项工作的诀窍是什么?
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
您是否尝试过使用 RecordCount 属性 记录集来查找返回的行数?
Debug.Print rs.RecordCount
我终于找到了解决办法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
按预期工作!