VBA将数据从文件夹提取到Excel电子表格

时间:2018-10-15 12:27:03

标签: excel vba loops text-extraction

我编写了一个函数,该函数将从文本文件中提取特定数据到单元格C1和D1中。我现在希望它循环遍历一个文件夹,并将相同的数据分别提取到C&D列中。

我尝试扩展recordCount()函数以打开Extracted Resources文件夹中的所有文本文件,但循环似乎不正确。代码是:

Sub recordCount()
Dim text As String
Dim textline As String
Dim strPath As String
Dim strCurrentTxtFile As String

strPath = ActiveWorkbook.Path & "\Resources\Extracted Text Files\"
strCurrentTxtFile = Dir(strPath & "*.Txt")

'~~> Looping through all text files in a folder
Do While strCurrentTxtFile <> ""

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

    '~~> Sets the Text and length to look for in files
    Header = InStr(text, "HH")
    Rcount = InStr(text, "RECORD COUNT")

    '~~> Writes them to workbook
        Range("C" & I).Value = Mid(text, Header + 80, 6)
        Range("D" & I).Value = Mid(text, Rcount + 14, 9)
    Loop
End Sub   

“ Do While”和“ Close#1”代码行之间出现问题。 我对此不好,所以请保持友好:)

1 个答案:

答案 0 :(得分:0)

我的信誉点不足以添加评论-但我的猜测是您的答案在这篇文章中:Loop through files in a folder using VBA?希望能帮上忙。