用于抓取文件夹中所有文件的VBA代码找不到文件



我正在尝试设置一个宏,以将文件夹中的所有 excel 文件拉入访问数据库。我有下面的代码,但是当我运行宏时,它错误地进入"未找到文件",因此intFile = 0。但是,所选文件夹中有文件。为什么找不到他们?我想我也搞砸了链接部分,但一次一个问题。我显然对 VBA 很陌生,所以任何帮助将不胜感激!谢谢

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 = "S:LOGPURCHASIDaniel BinkoskiOutlook AttachmentsR7398Z Look Forward Daily Snapshot"
'FileName
Dim strFile As String
'Array
Dim strFileList() As String
'File Number
Dim intFile As Integer
Sub Sample()
    strFile = Dir(strPath & "*.xlsx")
    'Looping through the folder and building the file list
    strFile = Dir(strPath & "*.xlsx")
    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, "A1:M50"
    Next
    MsgBox UBound(strFileList) & "Files were linked"
End Sub

尝试:

strFile = Dir(strPath & "*.xlsx", vbNormal)

或在 strPath 值上添加最后一个"\"

您需要另一个路径分隔符来显示您正在查找目录,而不是目录。

我经常使用这样的东西:

Dir(strPath & IIf(Right(strPath, 1) = "", vbNullString, ""))

作为检查以确保路径始终以尾随反斜杠结尾。

最新更新