2016-07-29 83 views
1

背景:
我需要打開一個Access文件並獲取信息在那裏,以與我的Excel電子表格中的數據進行比較。
我正在使用Microsoft Office 15.0 Access數據庫引擎對象庫而不是Microsoft DAO對象庫。
問題:
雖然我可以用下面的代碼粘貼所有的數據,出於某種原因,它開始在「行2」忽略標題。在Excel中Accesss搜索標題在訪問數據庫

Sub Sample() 
Const PathToDB = "C:\...\AccessFile.accdb" 
Const TitleSampleTable = "Sample Table" 
Dim BDSample As Database 
Dim SampleTable As Recordset 
Dim SampleTableDef As TableDef 
Dim CounterTitles As Long 
Dim CounterRows As Long 
Dim ColToPasteIn As Long 
Dim RowToPasteIn As Long 
    Set BDSample = DBEngine.Workspaces(0).OpenDatabase(PathToDB) 
    Set SampleTable = BDSample.OpenRecordset(TitleSampleTable, dbOpenDynaset) 
    Set SampleTableDef = BDSample.TableDefs(TitleSampleTable) 

    For CounterTitles = 0 To SampleTableDef.RecordCount 
    RowToPasteIn = RowToPasteIn + 1 
    ColToPasteIn = 1 
    For CounterRows = 0 To SampleTable.Fields.Count 
    With Sheets(TitleSampleTable) 
    .Cells(RowToPasteIn, ColToPasteIn).Value = SampleTable.Fields(CounterRows) 'this is starts in the "body" of access, I can't figure a way to retrieve titles! 
    ColToPasteIn = ColToPasteIn + 1 
    End With 
    Next CounterRows 
    SampleTable.MoveNext 
    Next CounterTitles 
    Set BDSample = Nothing 
    Set SampleTable = Nothing   
    Set SampleTableDef = Nothing 
End Sub 


的樣本數據

enter image description here

樣本數據

enter image description here


問題:
我如何GE t的標題值?

回答

1

你可以得到字段名和填充行1

For i = 0 To SampleTable.Fields.Count - 1 
    Sheets(TitleSampleTable).Cells(1, i + 1) = SampleTable.Fields(i).Name 
Next i 

然後你就可以從第2行以後填充的日期,你最初做

+0

哈哈,夠簡單吧!謝謝! – Sgdva