VBA将Excel电子表格链接到Access

时间:2012-05-22 14:01:01

标签: excel vba excel-vba

我正在Access 2010中的VBA中创建一个代码,用于链接excel表并将它们放入访问表中。我一直在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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

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

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

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

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

答案 2 :(得分:0)

你可以尝试做,在我看来这是一个简单的方法

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