什么是VBA代码导入选定的电子表格从excel文件到访问2007年表

我需要VBA代码将选定的电子表格从多个Excel文件导入访问2007表。 谁能帮忙?

这是迄今为止的代码。

Option Compare Database Option Explicit Const strPath As String = "C:\Users\person\Documents\files.xlsx" Dim strFile As String Dim strFileList() As String Dim intFile As Integer Sub Sample() strFile = Dir(strPath & "*.xls") strFile = Dir(strPath & "*.xls") While strFile <> "" 'adding files to the list intFile = intFile + 1 ReDim Preserve strFileList(1 To intFile) strFileList(intFile) = strFile strFile = Dir() If intFile = 0 Then MsgBox "No Files Found" Exit Sub End If 'going through the files and linking them to access For intFile = 1 To UBound(strFileList) DoCmd.TransferSpreadsheet acLink, , _ strFileList(intFile), strPath & strFileList(intFile), True, "A5:J17" Next MsgBox UBound(strFileList) & "Files were linked" End Sub 

我不明白这个代码是怎么回事,但是我的直觉是没有达到你期望的水平。

你声明一个常量, strPath

 Const strPath As String = "C:\Users\person\Documents\files.xlsx" 

稍后,将“* .xls”连接到该常量,并将其传递给Dir()函数。

 Sub Sample() strFile = Dir(strPath & "*.xls") 

我认为你应该尝试Debug.Print在这一点上…

 Debug.Print strPath & "*.xls" 

…因为你给Dir()的string使它等价于这个语句:

 strFile = Dir("C:\Users\person\Documents\files.xlsx*.xls") 

我怀疑是否匹配任何你想处理的Excel文件。

看下面的代码大纲是否有用。 我看不到需要先填充数组,然后循环访问数组以链接电子表格。 我不明白你为什么在这里需要一个数组。 如果可以,避免它,因为代码会更简单, ReDim Preserve是一个性能杀手。

 Sub Sample2() Const cstrFolder As String = "C:\Users\person\Documents\" Dim strFile As String Dim i As Long strFile = Dir(cstrFolder & "*.xls") If Len(strFile) = 0 Then MsgBox "No Files Found" Else Do While Len(strFile) > 0 Debug.Print cstrFolder & strFile ' insert your code to link to link to it here ' i = i + 1 strFile = Dir() Loop MsgBox i & " Files were linked" End If End Sub