获取文件夹中所有文件的VBA代码无法查找文件

时间:2015-04-13 23:01:52

标签: vba ms-access

我正在尝试设置一个宏来将文件夹中的所有Excel文件拉入访问的数据库中。我有下面的代码,但是当我运行宏时,它会错误地显示为“No Files Found”,因此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:\LOG\PURCHASI\Daniel Binkoski\Outlook Attachments\R7398Z 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

1 个答案:

答案 0 :(得分:1)

尝试:

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

或在strPath值

上添加最后一个“\”

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

我经常使用类似的东西:

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

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