关于每个单独的文件名,如何从多个文本文件中提取数据?

How do I extract data from multiple text files, in respect to each individual filename?

我需要多个文本文件中的一个值。这些文本文件以 5 位数的文件名存储在一个文件夹中(大约 1000 个文件),我想创建一个宏,它扫描该文件夹中的文件子集,然后提取单个欧元值。

我进行了提取部分,但我还不能通过不同的文件名循环这个过程,因为我对 VBA 还很陌生。

Sub ExtractData()
    Dim myFile As String, text As String, textline As String, Data As Integer, filename As String
    Dim myFolder As String

    myFolder = "C:\Folder\"
    filename = Range("A1").Value & ".txt"
    myFile = "C:\Folder\" & filename & ""

    Open myFile For Input As #1
    Do Until EOF(1)
        Line Input #1, textline
        text = text & textline
    Loop
    Close #1

    Data = InStr(text, "Euro")
    Range("B1").Value = Mid(text, Data + 6, 4)

End Sub

如果有人能指出正确的方向,我将不胜感激。 问候

您可以使用 Scripting.FileSystemObject to iterate the files in the target folder, use the Like 运算符来验证文件名,然后像往常一样从每个文件中获取值。

这应该有效:

Sub ExtractData()
    Dim folderPath As String, filePath As String
    Dim textline As String, data As Integer
    folderPath = "C:\Folder\"

    Dim oFso As Object: Set oFso = CreateObject("Scripting.FileSystemObject")
    Dim oFolder As Object: Set oFolder = oFso.GetFolder(folderPath)
    Dim oFiles As Object: Set oFiles = oFolder.Files
    Dim oFile As Object

    Dim counter As Integer
    For Each oFile In oFiles
        If Not oFile.Name Like "#####.txt" Then GoTo ContinueFor

        data = 0
        counter = counter + 1
        Range("A" & counter).Value = oFile.Name
        filePath = folderPath & oFile.Name

        Open filePath For Input As #1
            Do Until EOF(1) Or data > 0
                Line Input #1, textline
                data = InStr(textline, "Euro")
            Loop
        Close #1

        If data > 0 Then Range("B" & counter).Value = Mid(textline, data + 6, 4)
ContinueFor:
    Next
End Sub

这将从包含单词 "Euro" 的第一行中提取目标值。如果您尝试提取的值在同一行中是 而不是 ,您可以阅读整个文本(类似于您最初所做的),然后提取您想要的值:

Dim allText As String
' ...
' ...

Open filePath For Input As #1
    allText = Input(LOF(1), 1)
Close #1

data = InStr(allText, "Euro")
If data > 0 Then Range("B" & counter).Value = Mid(allText, data + 6, 4)

可能有更好的方法,但这完全取决于您的文件结构(您没有显示)。例如,如果目标值在下一行,并且你知道它在该行的位置,你可以使用上面的原始代码读取包含单词 "Euro" 的行,读取下一行,然后提取值。