【发布时间】:2016-08-03 00:46:22
【问题描述】:
我需要将多个 Excel 电子表格导入 Access 表。目前的电子表格如下所示:
ID | Year | Sales | Commissions
-- | ---- | ----- | -----------
1 | 2016 | 1,000 | 100
2 | 2016 | 2,000 | 200
3 | 2016 | 3,000 | 300
4 | 2016 | 1,000 | 300
它们需要看起来像这样:
ID | Name | Year | Month | Sales | Commissions | Discount | Net Sales | %
-- | ---- | ---- | ----- | ----- | ----------- | -------- | --------- | -
1 | John | 2016 | 2 | 1,000 | 100 | | |
2 | Mary | 2016 | 2 | 2,000 | 200 | | |
3 | Jake | 2016 | 2 | 3,000 | 300 | | |
4 | Bob | 2016 | 2 | 1,000 | 300 | | |
最后三列将是空白的。姓名(“John,Mary...”)将在另一个电子表格上使用基于 ID 的查找,但这可以稍后在 Access 中完成。顶部的 3 行也必须删除。月份(“2”)将位于 Excel 文件的文件路径中。这将是文件名中唯一的数字。即,“2”代表二月。所有电子表格都将位于同一个文件夹中。每个 Excel 工作簿都有一个电子表格标题“DataSheet”。这是将从每个工作簿中导入的电子表格。
我可以在 Access 中编写一个脚本来完成所有这些吗?
到目前为止,我已经为 Excel 宏找到了这个:
Sub Macro2()
Rows("1:3").Select
Range("A3").Activate
Selection.Delete Shift:=xlUp
Columns("B:B").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("B1").Select
ActiveCell.FormulaR1C1 = "Name"
Columns("D:D").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("D1").Select
ActiveCell.FormulaR1C1 = "Month"
Range("G1").Select
ActiveCell.FormulaR1C1 = "Discount"
Range("H1").Select
ActiveCell.FormulaR1C1 = "Net Sales"
Range("I1").Select
ActiveCell.FormulaR1C1 = " %"
Range("G2").Select
End Sub
Here's something 这样会导入多个文件:
Dim strPathFile As String, strFile As String, strPath As String
Dim strTable As String
Dim blnHasFieldNames As Boolean
blnHasFieldNames = False
strTable = "tablename"
strFile = Dir(strPath & "*.xls")
Do While Len(strFile) > 0
strPathFile = strPath & strFile
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
strTable, strPathFile, blnHasFieldNames
strFile = Dir()
Loop
【问题讨论】:
标签: excel vba ms-access macros