找不到目录中某些文件的运行时错误53文件

时间:2019-05-30 00:27:38

标签: excel vba

我编写了一个程序,提示用户选择一个装有.txt文件的文件夹,然后提取信息。

有些文件找不到,并且给我一个运行时错误53文件,尽管该文件位于文件夹中。

调试指向“打开输入为#1的MyFile”行。

如果我指定文件路径并运行宏,它将提取信息,以便文件路径正确。

我看了这个解决方案

Excel VBA - Run-time error '53': File not found. But file was found

基本上指定了一个目录,然后尝试从该目录读取每个文件,但出现相同的错误。

这是原始代码,提示用户选择文件夹而不是读取文件夹中的每个文件。

Sub read()
'PURPOSE: Send All Data From Text File To A String Variable

    Dim TextFile As Integer
    Dim FilePath As String
    Dim FileContent As String


    Dim MyFolder As String, MyFile As String

'Opens a file dialog box for user to select a folder

    With Application.FileDialog(msoFileDialogFolderPicker)
       .AllowMultiSelect = False
       .Show
       MyFolder = .SelectedItems(1)
       Err.Clear
    End With


'create a new object for files in that folder and apply the for/loop as below
    Dim objFSO As Object
    Dim objFolder As Object

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFSO.getFolder(MyFolder)

    Dim fls As Object
    Dim i As Integer
    i = 1
    For Each fls In objFolder.Files

'File Path of Text File

    MyFile = Dir(MyFolder & "\" & fls.Name, vbReadOnly)

'Determine the next file number available for use by the FileOpen function

    TextFile = FreeFile


'Open the text file

    Open MyFile For Input As #1

1 个答案:

答案 0 :(得分:0)

通过使用该行来实际剥离其路径的文件名

MyFile = Dir(MyFolder & "\" & fls.Name, vbReadOnly)

简单地做到

MyFile = MyFolder & "\" & fls.Name