在 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。完成后。您应该在新表中拥有所有数据。

希望这可以帮助 !

相关内容