2012-12-17 25 views
2

我需要的VBA代码汇入指定的电子表格从多个Excel文件到2007年的访问表。 任何人都可以帮忙吗?什么是VBA代码,以从Excel导入文件中选择电子表格到Access 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 
+1

您对发布的代码有什么问题? –

+0

只需检查这两个 [1]:http://stackoverflow.com/questions/7405261/import-an-excel-worksheet-into-access-using-vba [2]:http://stackoverflow.com/questions/10380312/loop-through-files-in-a-folder-using-vba – Spas

回答

3

我一直不明白这是怎么回事与该代码的,但我的预感是它不会做你期望的。

声名的常量,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()字符串使其等效于本声明:

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 
+0

感谢Tim的帮助。 – user1911206

相关问题