2017-09-09 134 views
1

我試圖從MS訪問中檢索數據以形成數據庫。但是記錄集的recordcount屬性始終返回-1,但出於其他目的,代碼工作正常。ADODB記錄集記錄計數總是返回-1

我使用的代碼如下: `子datarecordset()

Dim cn As adodb.Connection 
Dim oRs As adodb.Recordset 
Set cn = CreateObject("ADODB.Connection") 
DBPath = "C:\[databse path]" & "\[database name].accdb" 
dbWs = "[excel sheet name]" 
scn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBPath 
dsh = "[" & "[excel sheet name]" & "$]" 
cn.Open scn 
Dim sSQL As String 

Dim F As Integer 

sSQL = "Select 'W',a.[Subledger],NULL,sum(a.[Amount]) from GL_Table a where a.[Opex_Group] = 10003 and year(a.[G/L Date]) = " & Year(Sheets("Repairs").Cells(1, 4)) & " and month(a.[G/L Date]) = " & Month(Sheets("Repairs").Cells(1, 4)) 
sSQL = sSQL & " group by " & "a.[Subledger],(year(a.[G/L Date])),(month(a.[G/L Date]))" 
Set oRs = cn.Execute(sSQL) 
Debug.Print oRs.RecordCount 
oRs.Close 
....... further code to print to excel here 

cn.Close 
End Sub` 

該代碼將在記錄中獲取數據,並在Excel寫。但是由於recordset屬性沒有返回記錄計數,因此無法將記錄集中各個字段的值打印到Excel工作表的不同單元格中。

我在google上搜索並瞭解到我需要聲明記錄集類型,爲此我必須使用connection.open來代替connection.execute。但我試圖改變代碼,然後給出錯誤對象變量或變量未定義。

任何快速幫助將受到歡迎。謝謝。

+1

請參見[recordcounterror](http://www.adopenstatic.com/faq/) recordcounterror.asp)和[recordcountalternatives](http://www.adopenstatic.com/faq/recordcountalternatives.asp)來解決。 – BitAccesser

回答

1

@BitAccesser的鏈接提供了一個有效的解決方案。快速在你的情況怎麼樣,到實現: 而不是Set oRs = cn.Execute(sSQL)

Set oRS = CreateObject("ADODB.Recordset") 
oRS.CursorLocation = adUseClient 
oRS.Open sSQL, cn 

ADO的RecordCount屬性返回-1時,ADO無法確定記錄數,或者如果提供者或遊標類型不支持總記錄。最後一種情況對於這種情況是正確的。

爲了避免這種情況,有幾種解決方案。最簡單的就是使用客戶端遊標,我剛剛演示了這個遊標,但是通過@BitAccesser提供了更多替代解決方案

+0

它解釋了這個問題。你應該在你的回答中引用這個(鏈接死之前)。 – BitAccesser

+0

很高興..這工作。謝謝。 –

+1

@BitAccesser無法找到該網站頁面的許可證信息(有版權標誌,但沒有規範)。因此,所有權利都是爲作者保留的,並且在他的某篇文章上覆制一大段內容可能會被視爲侵犯版權(即使在引用時)。我將根據[MSDN](https://docs.microsoft.com/en-us/sql/ado/reference/ado-api/recordcount-property-ado)寫出一個快速解釋。 –