VBA将Excel电子表格链接到Access

我在Access 2010的VBA中创build一个代码,将excel表链接到访问表中。 我一直在strFile = Dir(StrPath &"*.xls")之外的过程中得到一个无效的strFile = Dir(StrPath &"*.xls")它一直告诉strPath is invalid outside procedure

请帮忙。

 Option Compare Database Option Explicit 'code will link to excel and pull site survey files into access tables 'Setting the path for the directory Const strPath As String = "C:\Users\cparson\Documents\Survey_Eqpm\SiteSurveyData.xlsx" 'FileName Dim strFile As String 'Array Dim strFileList() As String 'File Number Dim intFile As Integer 'Looping through the folder and building the file list 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() Wend 'checking to see if files where found 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 

你有一个End Sub但没有过程名称?

 Option Compare Database Option Explicit Const strPath As String = "C:\Users\cparson\Documents\Survey_Eqpm\SiteSurveyData.xlsx" Dim strFile As String Dim strFileList() As String Dim intFile As Integer Sub Sample() '<~~ You are missing this... strFile = Dir(strPath & "*.xls") '~~> Rest of your code End Sub 

我知道这是一个老问题,但是我在谷歌search中遇到了这个问题,并且意识到在strPathvariables中已经有了.xlsx扩展名,但是也将它添加到stringvariablesstrFile

 Const strPath As String = "C:\Users\cparson\Documents\Survey_Eqpm\SiteSurveyData.xlsx" strFile = Dir(strPath & "*.xls") 

我可能是错的,但只是想指出。

你也可以试试ADO,这是我的一个简单的方法

 YourConnObj.execute "SELECT * INTO YourTableName from [Excel 14.0;DATABASE=c:\temp\data copy.xlsx].[Sheet1]"