自动将不同的Excel文件导入MS Access 2010表

时间:2014-02-05 13:20:50

标签: vba ms-access access-vba ms-access-2010

我想将所有Excel文件(包含不同的数据和列)从某个目录导入MS Access 2010数据库,为每个文件创建新表。我找到了将文件导入一个表的代码:

Option Compare Database
Option Explicit

Function DoImport() 

Dim strPathFile As String, strFile As String, strPath As String
 Dim strTable As String
 Dim blnHasFieldNames As Boolean

 ' Change this next line to True if the first row in EXCEL worksheet
 ' has field names
 blnHasFieldNames = True

 ' Replace C:\Documents\ with the real path to the folder that
 ' contains the EXCEL files
 strPath = "C:\Documents and Settings\myName\My Documents\Access Test\"

 ' Replace tablename with the real name of the table into which
 ' the data are to be imported
 strTable = "tablename"

 strFile = Dir(strPath & "*.xls")
 Do While Len(strFile) > 0
       strPathFile = strPath & strFile
       DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
             strTable, strPathFile, blnHasFieldNames

 ' Uncomment out the next code step if you want to delete the
 ' EXCEL file after it's been imported
 '       Kill strPathFile

       strFile = Dir()
 Loop

End Function

但我每次都需要创建新表。在VBA中可以吗?

3 个答案:

答案 0 :(得分:3)

我认为您需要做的就是每次执行strTable之前更改目标表名称(DoCmd.TransferSpreadsheet的值)。

在评论中,您说您希望从工作簿文件名派生表名。并且,每次通过循环时,另一个变量(strFile)包含文件名。所以我认为您可以从该文件名中删除文件扩展名并将其用作Access表名。

这是一个立即窗口示例,演示了如何做到这一点......

strFile = "foo.xls"
strTable = Left(strFile, Len(strFile) - 4)
? strTable
foo

如果这种方法合适,请修改VBA代码中的循环,例如此(未经测试的)代码段......

strFile = Dir(strPath & "*.xls")
Do While Len(strFile) > 0
    strPathFile = strPath & strFile
    strTable = Left(strFile, Len(strFile) - 4)
    DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
        strTable, strPathFile, blnHasFieldNames
    strFile = Dir()
Loop

答案 1 :(得分:1)

我曾经是一个MOS Access 2003.现在每个人都在使用2010,但很多事情都没有改变。

进行手动导入或导出时,可以将布局保存为规范。

此过程可以通过宏自动完成。

请查看以下链接,了解更多详情和步骤。

http://office.microsoft.com/en-us/access-help/run-a-saved-import-or-export-operation-HA001226020.aspx?CTT=5&origin=HA001226307

至于其他东西,按钮,模块等,请先阅读在线帮助/文档。

我们随时为您提供帮助,但不为您做好工作。

Ĵ

答案 2 :(得分:1)

好的,我不知道我的电脑是否存在当前办公室CU的问题。

http://msdn.microsoft.com/en-us/library/office/ff192475(v=office.14).aspx

以下是如何使用ImportExport宏的链接。用于在宏部分。

我确实读到你必须相信这个位置。所以我尝试了我的位置c:\ msdn加上向导的默认值。

enter image description here

仍然无法选择它。

我尝试创建一个规范,看看是否需要一个显示选项,没有骰子。

但是,有一个DoCmd.TransferText和DoCmd.TransferSpreadSheet。

两者都允许你导入。

创建一个功能。从宏(RunCode)调用该函数。另一种方法是创建主菜单表单。有一个按钮。在单击命令上,运行代码。

如果您要显示ImportExportData宏,请告诉我。我认为这是一个错误。我需要删除最新的累积更新,然后再试一次。

enter image description here

相关问题