【问题标题】:VBA code to grab all files in folder is not finding files获取文件夹中所有文件的 VBA 代码未找到文件
【发布时间】:2015-04-13 23:01:52
【问题描述】:

我正在尝试设置一个宏以将文件夹中的所有 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:\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

【问题讨论】:

    标签: vba ms-access


    【解决方案1】:

    尝试:

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

    或在您的 strPath 值上添加最后一个“\”

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

    我经常使用类似的东西:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-29
      • 1970-01-01
      • 1970-01-01
      • 2011-08-07
      相关资源
      最近更新 更多