2012-06-12 148 views
3

我想在Microsoft Access中編寫一個VBA腳本,它將與Excel工作表連接,循環遍歷行,然後循環行中的單元格,然後將信息拉回到Access表中。MS Access VBA腳本與Excel接口

下面是一些須藤代碼 -

For Each Row 
    For Each Cell in the Row 
     Read the Cell 
     Create a new Record in the Access table with the info from the cell 
    End For Each 
End For Each 

你可以看到在下面的圖片最終結果的一個簡單的例子。

我們有─什麼

enter image description here

什麼是needed-

enter image description here

我以前有編碼,但從未在VBA;所以任何幫助將不勝感激!謝謝你的幫助!!!

+0

請閱讀[Remou寫道](http://stackoverflow.com/a/10999515/190829),已經有一個內置的方法來做到這一點。即使將範圍讀入數組而不是循環遍歷每個單元格會更好。 – JimmyPena

回答

2

首先按照@Remou的建議創建一個到Excel工作表的鏈接。在以下示例中,我將該鏈接命名爲「tblExcelData」。然後,「tblDestination」將根據您的要求爲工作表行的每個「單元格」存儲單獨的記錄。在tblDestination,Seq#是長整數,並且Field NameField Value都是文本。

Public Sub foo20120612a() 
    Dim db As DAO.Database 
    Dim rsSrc As DAO.Recordset 
    Dim rsDest As DAO.Recordset 
    Dim fld As DAO.Field 

    Set db = CurrentDb 
    Set rsSrc = db.OpenRecordset("tblExcelData", dbOpenSnapshot) 
    Set rsDest = db.OpenRecordset("tblDestination", _ 
     dbOpenTable, dbAppendOnly) 
    Do While Not rsSrc.EOF 
     For Each fld In rsSrc.Fields 
      If fld.Name <> "Seq#" Then 
       With rsDest 
        .AddNew 
        ![Seq#] = CLng(rsSrc![Seq#]) 
        ![Field Name] = fld.Name 
        ![Field Value] = fld.value 
        .Update 
       End With 
      End If 
     Next fld 
     rsSrc.MoveNext 
    Loop 
    rsDest.Close 
    Set rsDest = Nothing 
    rsSrc.Close 
    Set rsSrc = Nothing 
    Set db = Nothing 
End Sub 
+0

你。是。 A.救命稻草。 – ohGosh

2

我建議您使用DoCmd的各種嚮導或TransferSpreadsheet方法鏈接Excel表格,並使用鏈接的Excel表格簡單地運行動作查詢。

聯合查詢是必需的。讓我們打電話給你的鏈接電子表格。

SELECT * INTO Table1 
FROM (
    SELECT [Seq#], "Name" As [Field Name], [Name] As [Field Value] 
    FROM t 
    UNION ALL 
    SELECT [Seq#], "Location" As [Field Name], [Location] As [Field Value] 
    FROM t 
    UNION ALL 
    SELECT [Seq#], "Car" As [Field Name], [Car] As [Field Value] 
    FROM t) imp 

INSERT INTO Table1 
SELECT * FROM (
    SELECT [Seq#], "Name" As [Field Name], [Name] As [Field Value] 
    FROM t 
    UNION ALL 
    SELECT [Seq#], "Location" As [Field Name], [Location] As [Field Value] 
    FROM t 
    UNION ALL 
    SELECT [Seq#], "Car" As [Field Name], [Car] As [Field Value] 
    FROM t) imp 

您可以通過刪除字段和列名稱中的空格和保留字來簡化生活。

如上所示,列出使用星號(*)的字段通常會更好。

+0

我已經使用該向導從Excel中提取數據,並且效果很好。不過,我之前從未使用動作查詢來組織數據。您能否詳細說明如何使用動作查詢來將數據格式化爲圖片的顯示方式? – ohGosh