vba - 如何使用 TransferSpreadsheet 将源文件的文件名添加到每行的第一个单元格?
问题描述
我正在尝试将源 excel 文件的文件名添加到导入 Access 表的每一行的第一个单元格中。
我搜索了网络,但无法找到我想要实现的目标。
Public Function Import()
Dim path As String
Dim fileName As String
path = "C:\Users\" & NetworkUser() & "\Documents\TestDatabase\"
fileName = Dir(path & "\*.xlsx")
While fileName <> ""
DoCmd.TransferSpreadsheet acImport, 10, "Table1", path & fileName, True, "A4:S28"
fileName = Dir()
Wend
Call DeleteEmptyRows
End Function
我想要完成的一个例子:
从 Excel 文件输入
Stone | 5 | No
Door | 1 | No
Table | 2 | No
Chair | 6 | No
Fuel | 12 | Yes
访问表上的输出
example1.xlsx | Stone | 5 | No
example1.xlsx | Door | 1 | No
example2.xlsx | Table | 2 | No
example2.xlsx | Chair | 6 | No
example3.xlsx | Fuel | 12 | Yes
解决方案
将电子表格导入到包含filename
文本值字段的现有表中,然后运行一个简单的update
查询以使用电子表格的文件名填充该filename
字段。
例如,假设您的表Table1
包含一个名为 的附加字段filename
,您可以在该方法之后运行update
查询DoCmd.TransferSpreadsheet
:
While fileName <> ""
DoCmd.TransferSpreadsheet acImport, 10, "Table1", path & fileName, True, "A4:S28"
DoCmd.RunSQL "update table1 set table1.filename = '" & fileName & "' where table1.filename is null"
fileName = Dir()
Wend