2014-02-05 132 views
2

我想将某些目录下的所有Excel文件(具有不同的数据和列)导入到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中可能吗?

+0

回复:“如果有人可以提供创建按钮,模块和运行的步骤示例,我会非常感激。” - 哇。如果这不是“太宽泛”,我不知道*是什么*。 –

+0

我一直在网上浏览足够长的时间,但还没有找到关于如何创建按钮并将其与模块链接的示例。我相信它不会花很长时间来快速指导。无论如何,我的主要问题是关于循环创建新表。 –

+0

你想如何命名新表? – HansUp

回答

3

我认为,所有你需要做的是你做DoCmd.TransferSpreadsheet前更改目标表的名称(strTable值)各一次。

在一个评论中,你说你想从工作簿文件名派生表名。而且,每次通过循环时,另一个变量(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 
+0

正是我想要的,那么容易。非常感谢! –

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

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

我们在这里帮助,但不是为你做的工作。

Ĵ

+0

好吧,编辑我的问题听起来不太恳求:)谢谢你的链接,但仍然有一种方法来导入单个文件,覆盖同一张表。 –

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

+0

从宏调用我的功能,它工作正常,感谢您的帮助! –

相关问题