在 Access 中將一個表格中的欄位合併到另一表中的一個字段

在 Access 中將一個表格中的欄位合併到另一表中的一個字段

我正在嘗試組合一個表中的多個字段,該表具有用戶ID 和水平排列的10 列數據,以垂直顯示在兩個字段中,其中一個字段對應於用戶ID,另一個字段對應於10 個垂直字段。在第二個表中,使用者名稱將重複原始表中 10 個水平欄位中的輸入次數。

我的例子基本上是:

MainT
`````
User ID
otherfields
Invoice1
:
Invoice10

想要放入新表中:

InvoicesT
`````````
User ID
Invoices

我需要知道如何從 MainT 獲取數據:

User    |   Othr Fld    |   Invoice1    |   Invoice2    |   Invoice3
--------+---------------+---------------+---------------+-------------
1       |   JF          |   Paid        |   Past Due    |  Civil Court
2       |   JN          |   Paid        |   Paid        |  Past Due
3       |   MO          |   Past Due    |   Paid        |  Paid

按照我規定的方式填充到 InvoicesT 中。

User    |   Invoice
--------+--------------
1       |   Paid
1       |   Past Due 
1       |   Civil Court
2       |   Paid
2       |   Past Due

ETC。

答案1

我不記得有一個簡單的查詢可以按照您想要的方式轉換資料。我首先想到的是交叉表查詢,但這不是您可以使用現有資料結構完成的事情。我想為您提供一個 VBA 解決方案,因為我覺得您在重新設計表格資料方面走在正確的軌道上。

為了使該解決方案發揮作用,首先建立第二個表InvoicesT,其中包含以下欄位。

InvoicesT
`````````
Field Name          |   Data Type
--------------------+------------------
invoiceID           |   Autonumber 
UserID              |   Number
InvoiceCategory     |   Text

接下來,將以下 Sub 複製到標準模組中。

Public Sub transferData()
    Dim oldTbl As DAO.Recordset, newTbl As DAO.Recordset
    Dim dbObj As DAO.Database
    Dim fCtr As Integer

    Set dbObj = CurrentDB()

    'Open the MainT table to read the information.
    Set oldTbl = dbObj.OpenRecordSet("SELECT [User ID], Invoice1, Invoice2, Invoice3, Invoice4, " & _
                                     "Invoice5, Invoice6, Invoice7, Invoice8, Invoice9, Invoice10 FROM MainT")

    'Open the InvoicesT to write new information into.
    Set newTbl = dbObj.OpenRecordSet("InvoicesT")

    'Loop through the list of all entries in MainT
    Do While Not oldTbl.EOF
        'This will loop through the fields to create one entry for each field.
        'You can change the number 10 to any number depending on the Invoice fields in the table. 
        For fCtr = 1 To 10
            'I have put an IF condition to make sure there are not many empty records for a UserID
            'If the Invoice(n) is not available for a particular user, then it does not create an entry. 
            If Len(oldTbl.Fields("Invoice" & fCtr) & vbNullString) > 0 Then
                With newTbl
                    .AddNew
                    .Fields("UserID") = oldTbl.Fields(0)
                    .Fields("InvoiceCategory") = oldTbl.Fields("Invoice" & fCtr)
                    .Update
                End With
            End If
        Next
        'Go to the next record when one user is done with
        oldTbl.MoveNext
    Loop

    'Clean up
    Set newTbl = Nothing
    Set oldTbl = Nothing
    Set dbObj = Nothing
End Sub

現在,一旦您使用類似名稱保存了模組mod_TransferTables並編譯了它。轉到您的直接視窗(CTRL + G)。然後只需鍵入transferData並點擊ENTER,這可能需要一段時間,具體取決於表中的記錄數MainT。一旦完成。您應該擁有新表中的所有資料。

希望這可以幫助 !

相關內容