2012-05-22 95 views
0

我在Access 2010的VBA中创建了一个代码,用于链接Excel工作表并将它们放入访问表中。我在strFile = Dir(StrPath &"*.xls")以外的程序中一直收到无效它一直告诉strPath is invalid outside procedureVBA将Excel电子表格链接到Access

请帮忙。

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 

回答

1

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

好,非常感谢你 – user1410368

0

你可以尝试过ADO,它在我的opnion一个简单的方法

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

我知道这是一个老问题,但我在谷歌搜索碰到它,并意识到你已经有strPath变量中的.xlsx扩展名,但也将其添加到字符串变量strFile

Const strPath As String = "C:\Users\cparson\Documents\Survey_Eqpm\SiteSurveyData.xlsx" 

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

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

相关问题