2011-11-01 61 views
0

我有以下代碼:如何從excel中的記錄集中獲取數據?

Dim cn As Object 
Dim rs As Object 
Dim strSql As String 
Dim strConnection As String 
Dim AppPath As String 
Set cn = CreateObject("ADODB.Connection") 
AppPath = Application.ActiveWorkbook.Path 

Set rs = CreateObject("ADODB.RecordSet") 

strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _ 
    "Data Source=" & AppPath & "\Masterlist_Current_copy.accdb;" 

strSql = "SELECT [Neptune Number],[Description],[Manufacturer],[Manufacturer P/N] FROM [All Components];" 
cn.Open strConnection 
Set rs = cn.Execute(strSql) 

'Need Code here to get Info out of recordset 

我想獲得的信息指出,有查詢結果記錄被傾倒進去。我試圖找出如何查詢記錄集,並獲得「海王星數字」字段中具有特定值的行數。然後,我將在正在修改的工作表中插入正確數量的行。之後,我需要獲取該值的數據並將其插入到工作表中。

注:我不在乎是否使用記錄集,數據表或其他任何東西我只需要能夠做我上面描述的。請顯示代碼。

回答

1

最簡單的方式得到你我想你問去是修改你的SQL語句改變

strSql = "SELECT [Neptune Number],[Description],[Manufacturer],[Manufacturer P/N] FROM [All Components];" 

strSql = "SELECT [Neptune Number],[Description],[Manufacturer],[Manufacturer P/N] FROM [All Components] WHERE [Neptune Number] = 'Specific Value' ;" 

這將迫使SQL查詢只返回記錄你的需要。 .find方法可以用於過濾記錄集,但是我已經避免在這個實例中使用它,因爲它只是簡單地向db索要你想要的信息就更清潔。

處理您可以使用記錄以下

with rs 
    'will skip further processing if no records returned 
    if not (.bof and .eof) then 
     'assuming you do not need the headers 
     'loop through the recordset 
     do while not .eof 
      for i = 0 to .fields.count -1 
       'assuming the active sheet is where you want the data 
       cells(row, i + colOffset) = .fields(i).value 
      next 
      Rows(Row & ":" & Row).Insert 
      .movenext 
     loop 
    end if 
end with 

哪裏行數據的出發點和colOffset是數據的起始列。請注意,此代碼不會按照您在問題中指定的確切順序執行操作(我根據需要插入行,而不是先前計算記錄數。)

我已經避免使用.recordcount,因爲我根據數據庫使用它將不會返回正確的記錄數。

相關問題