【发布时间】:2019-12-12 09:34:37
【问题描述】:
(使用 MS Office Professional Plus 2016)
我调整了这个子过程,将 MS-Excel 文件/它们的第一个工作表(称为“表”)导入 MS-Access 数据库。代码导航到指定的文件夹并导入该文件夹中的所有 .xls 文件。所有 .xls 文件都具有相同的格式。我正在使用 DoCmd.TransferSpreadsheet 和 Do While。
但是,各个 .xls 文件中“表格”工作表中的相关数据从第 29 行开始,字段名称在第 28 行。
我的问题是:有没有办法只将第 28 行中的字段名称和第 29 行中的数据导入到最后一个非空行 - 一种将其包含在 Do While 中的方法?也许使用 TransferSpreadsheet 命令中的 Range 选项,但我不知道如何在“第 x 行到最后一个非空行”范围内表达。
Option Compare Database
Sub importfiles()
Dim blnHasFieldNames As Boolean
Dim strWorksheet As String, strTable As String
Dim strPath As String, strPathFile As String
' Change this next line to True if the first row in EXCEL worksheet
' has field names
blnHasFieldNames = False
' Replace C:\Documents\ with the real path to the folder that
' contains the EXCEL files
strPath = "E:\importfiles\"
' Replace worksheetname with the real name of the worksheet that is to be
' imported from each file
strWorksheet = "Table"
' Import the data from each workbook file in the folder
strFile = Dir(strPath & "*.xls")
Do While Len(strFile) > 0
strPathFile = strPath & strFile
strTable = "tbl_" & Left(strFile, InStrRev(strFile, ".xls") - 1)
DoCmd.TransferSpreadsheet acImport, _
acSpreadsheetTypeExcel9, strTable, strPathFile, _
blnHasFieldNames, strWorksheet & "$"
' Uncomment out the next code step if you want to delete the
' EXCEL file after it's been imported
' Kill strPathFile
strFile = Dir()
Loop
MsgBox ("The sub was run.")
End Sub
Public Function runImport()
Call importfiles
End Function
(I slightly adapted this code from http://www.accessmvp.com/KDSnell/EXCEL_Import.htm#ImpWktFilesSepTbls)
EDIT:
[Type mismatch, see Max's answer][1]
[Screenshot of excel file][2]
[access table][3]
[Compile error(see Max's answer)][4]
[for max][5]
[for max2][6]
[for max3][7]
[1]: https://i.stack.imgur.com/PZFnl.png
[2]: https://i.stack.imgur.com/IjvKc.png
[3]: https://i.stack.imgur.com/jzOXu.png
[4]: https://i.stack.imgur.com/uHUTK.png
[5]: https://i.stack.imgur.com/slAeG.png
[6]: https://i.stack.imgur.com/g6fNr.png
[7]: https://i.stack.imgur.com/gFNqA.png
【问题讨论】:
-
据我所知,transferspreadsheet 只导入适合表格的行。如果您设置列定义,例如为第一行的“整数”并且 excel 为空或前 28 行中的文本,不会导入行。尝试找到一列,其中只有第 28:X 行满足特定要求,并将其设置在您的表格中。
-
感谢您的建议。我确实将第一列设置为整数,只有相关数据在工作表的第一列中有一个整数(数字)。我收到错误消息:运行时错误“2391”:目标表“Test1212”中不存在字段“F1”。 Transferspreadsheet 似乎并不关心这一点。也许有一些代码会在每次导入之前删除相应 excel 工作表中不相关的标题?
-
可以发一张excel的截图吗?
-
我添加了截图链接。