使用 VBA 遍历 Txt 文件 - DIR() 问题

Looping Through Txt Files using VBA - DIR() issue

我有以下代码,我试图修改特定文件夹中的一些 Txt 文件。我首先要检查循环是否有效。但是,当我 运行 宏时,代码只能读取第一个文件,然后在 strFileName = Dir() 处出现 运行time 5 错误。我不确定是什么问题。我能想到的唯一问题是我在两个模块表之间移动代码。文件夹位置保存在 excel 工作簿的 Sheet 1 的文本框中。

Sub Txt_File_Loop()
Public TextFile As String
Dim FolderLocation As String
Dim strFielName As String
Dim SaveLocation As String
'Location is present in a Text box
FolderLocation = Sheets(1).FolderLocationTXTBX.Text
strFileName = Dir(FolderLocation & " \ * ")
Do Until strFileName = ""
TextFile = FolderLocation & "\" & strFileName
Module2.Macro1
strFileName = Dir() 'ERROR is Here
Loop

End Sub

Sub Macro1()
Dim x As String
Open TextFile For Input As #1
Do Until EOF(1)
Line Input #1, textline
x = x & textline
Loop

Close #1
MsgBox x

End Sub

看看这些修改。他们似乎纠正了几件事并且 运行 很好。

Option Explicit

Sub Txt_File_Loop()
    Dim FolderLocation As String
    Dim strFileName As String
    Dim SaveLocation As String
    'Location is present in a Text box
    FolderLocation = Sheets(1).FolderLocationTXTBX.Text   'Environ("TMP")
    strFileName = Dir(FolderLocation & "\*.txt")
    Do Until strFileName = ""
        Debug.Print FolderLocation & "\" & strFileName
        Module2.Macro1 FolderLocation & "\" & strFileName
        strFileName = Dir() 'ERROR is Here
    Loop
End Sub

Sub Macro1(sFPFN As String)
    Dim x As String, textline As String
    Debug.Print sFPFN

    Open sFPFN For Input As #1
    Do Until EOF(1)
        Line Input #1, textline
        x = x & textline
    Loop

    Close #1
    MsgBox x

End Sub

我将文件夹和文件名名称作为字符串类型参数传递。另外,我不知道为什么 (FolderLocation & " \ * " 中有多余的空格;我把它收紧了。有一些拼写错误和未声明的变量;这些可以通过模块代码 sheet 顶部的 Option Explicit¹ 来避免。在您的代码中练习标准缩进。如果没有别的,它肯定会提高可读性。


¹ 在 VBE 的工具 ► 选项 ► 编辑器 属性 页面中设置 需要变量声明 将把 Option Explicit 每个新创建的代码顶部的语句 sheet。这将避免愚蠢的编码错误,如拼写错误,并影响您在变量声明中使用正确的变量类型。没有声明的动态创建的变量都是 variant/object 类型。使用 Option Explicit 被广泛认为 'best practice'.