2011-08-17 31 views
0

我試圖在VBScript中使用ADODB來訪問Excel文件,以查找給定工作表中具有輸入數據的行數。到目前爲止,我的代碼顯示了工作表中的所有內容,但我不確定如何計算行數或直接使用查詢來查找行數。我想使用ADODB,因爲它不直接打開Excel文件,但如果這不是最好的方式,那麼我該怎麼做呢?謝謝。在VBScript中使用ADODB來查找Excel工作表中的行數?

Set adodb = CreateObject("ADODB.Connection") 
adodb.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _ 
       "test.xls" & ";Extended Properties=""Excel 8.0;IMEX=1;" & _ 
       "HDR=NO;" & """" 

Set result = adodb.Execute("Select * from [Sheet1$]") 

MsgBox result.GetString 

result.Close 
adodb.Close 
Set adodb = Nothing 
Set result = Nothing 

回答

0

添加的CursorLocation屬性連接對象。

更新時間:

'result.CursorLocation = 3 'adUseClient 
adodb.CursorLocation = 3 'adUseClient 

然後你就可以得到的行數。

MsgBox result.RecordCount 
+0

我得到了錯誤:當對象打開時不允許操作... for result.CursorLocation = 3 – ant

+0

對不起。它一定是adodb.CursorLocation = 3 –

+0

現在工作正常,歡呼! – ant

0

我得到這個就OK工作:

Sub testit() 

Dim ad As New adodb.Connection 
Dim result As New adodb.Recordset 

    ad.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _ 
    "Data Source=test.xls ;" & _ 
    "Extended Properties=Excel 8.0;" 

    result.Open "Select count(*) FROM [Sheet1$]", _ 
     ad, adOpenStatic, adLockOptimistic, adCmdText 

    Debug.Print "rows:" & result.GetString 

    result.Close 
    ad.Close 

End Sub 

(我改變了你的變量名ADODB,因爲它似乎衝突)。

相關問題