如何将数据从Excel导入Access并获取外键

时间:2015-05-21 07:48:20

标签: excel excel-vba ms-access import vba

我想将Excel表格中的数据导入预定义的Access表格。我有8个表,其中3个表依赖外键。因此,我希望能够在导入时获取这些外键,以便可以正确导入信息。

例如,表tblSubcomponents具有以下字段:   - 子组件ID(自动编号)   - SubcomponentNumber   - SubcomponentName   - MaterialField

字段SubcomponentID则是表tblBrushholderDetails上的外键。此表的字段包括:   - BHDetailsID(自动编号)   - BHID(外键)   - 子组件ID(外键)   - 零件/ BH

我已经查看了帖子:How to assign foreign keys in Access within imported table from Excel。但是,我正在考虑做一些更多的INSERT INTO和@@ IDENTITY ...这可能吗?

感谢您的投入! :)

1 个答案:

答案 0 :(得分:0)

我在类似情况下使用以下代码:

DB.Execute "insert into [Book to Tax import files] ([file name],[update date]) values (" & "'" & file.Name & "',#" & file.DateLastModified & "#);"
Source = DB.OpenRecordset("SELECT @@IDENTITY")(0)
DoCmd.TransferText , , "Book to Tax import Temp", Source_folder & "\" & file.Name

SQL = "INSERT INTO [Book to Tax Import data] ([source], Account, [Book Balance], [Book Adjustments], [Adjusted Book Balance], [Tax Reclass], [Balance After Tax Reclass], [Tax Adjustments], [Historical tax Adjustments], [Tax Balance] )"
SQL = SQL & "select " & Source & ",trim(F1),F2,F3,F4,F5,F6,F7,F8,F9 FROM [Book to Tax import temp] ;"

DoCmd.RunSQL SQL
DoCmd.DeleteObject acTable, "Book to Tax Import Temp"

在这种情况下,我基本上将文件名放入一个带有自动编号主键的表中。然后我使用@@ Identity检索该密钥,并在将数据附加到第二个表时将其用作外键。