2012-05-22 53 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") 

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

相關問題