0

我在 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
4

3 回答 3

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
于 2012-05-22T14:34:24.380 回答
1

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

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

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

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

于 2016-07-01T13:17:06.550 回答
0

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

YourConnObj.execute "SELECT * INTO  YourTableName from [Excel 14.0;DATABASE=c:\temp\data copy.xlsx].[Sheet1]"
于 2012-05-22T23:18:35.973 回答