首页 > 解决方案 > Excel VBA - 运行时错误“53”:找不到文件。但是找到了文件

问题描述

我有一个 Excel 表,它从一个充满 .txt 文档的文件夹中提取数据。上周五,它奏效了。没有改变。这周星期一,我收到运行时错误“53”:找不到文件。

有趣的是,当我单击“调试”时,它会突出显示我的代码中的一行,当我将鼠标悬停在“sFile”变量上时,它会告诉我它显然找不到的文件的名称......但它只有找到它才能知道它的名称......是的,我已经验证过,该文件确实存在。

Excel 工作表位于 H:\My Documents\Loma CW3 Reports\

数据 .txt 文件位于 H:\My Documents\Loma CW3 Reports\Product Statistics\

它应该提取的前 3 个文件是:

- PR20180912T153019.txt
- PR20180913T070005.txt
- PR20180913T153002.txt

如上所述,当我调试代码并将鼠标悬停在“Open sFile For Input As #1”行中的“sFile”时,它告诉我:

sFile = "PR20180912T153019.txt"

它只能知道它是否成功扫描了文件夹,因为我没有硬编码任何这些文件名。

我尝试删除该文件,将文件重命名为“apple”之类的单词,检查它是否变为只读(不)。我在这里陷入了一个循环,因为它像上周一样工作,并且与我本周打开它并尝试它时相比没有任何变化。

下面的代码:

Private Sub CommandButton1_Click()

' Dim myFile As String
Dim text As String, textLine As String
Dim sFile As String, rowTarget As Long

rowTarget = 2

' myFile = Application.GetOpenFilename()

sFile = Dir("H:\My Documents\Loma CW3 Reports\Product Statistics\" & "*.txt*")
Do Until sFile = ""
    Open sFile For Input As #1
    Do Until EOF(1)
        Line Input #1, textLine
        text = text & textLine
    Loop
    Close #1

    Do stuff here

    rowTarget = rowTarget + 1
    sFile = Dir()
    text = ""
Loop
End Sub

标签: excelvba

解决方案


我最终将目录指定为一个单独的变量,并在打开文件时将 sFile 名称附加到它上面。

Dim directory As String

directory = "H:\My Documents\Loma CW3 Reports\Product Statistics\"
sFile = Dir(directory & "*.txt*")

Do Until sFile = ""
    Open (directory & sFile) For Input As #1
    blah blah blah

谢谢@comintern


推荐阅读