VBA Excel循环文件夹文件以提取某些数据

时间:2014-07-29 07:54:44

标签: file vba excel-vba text-files excel

我是VBA的新手。我需要循环一个包含文本文件的文件夹,打开它们进行输入,然后从中提取一些特定数据。我成功地为一个文件做了这个。我需要一个想法来为文件夹做这个。谢谢 !

3 个答案:

答案 0 :(得分:1)

使用Dir()循环:

const path as string = "c:\blah\"
dim file As string 

file = Dir$(path & "*.txt")
do while Len(file) > 0
    debug.? "found "; path & file
    file = Dir$()
loop

答案 1 :(得分:0)

试试这个

Sub ShowFolderItems()
    Dim fs, f, f1, fc
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder("C:\")
    Set fc = f.Files
    For Each f1 In fc
        If InStr(1, f1.Name, ".txt") Then
        'Use your code here
        End If
    Next

End Sub

答案 2 :(得分:0)

我还需要从excel表中的文件中写出提取的数据,但我不想覆盖它,我必须在下面写入从前一个文件读取的数据 这是代码,但会覆盖先前文件中读取的数据。

Sub ShowFolderItems()
    Dim fs, f, f1, fc
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder("D:\")
    Set fc = f.Files
    For Each f1 In fc
       Open f1 For Input As #1
row_number = 0
row_number2 = 0

Do Until EOF(1)

Line Input #1, linefromfile

LineItems = Split(linefromfile, ",")
lineitems1 = Split(LineItems(0), "")

lineitems1 = Split(linefromfile, ":")
lineitems2 = Split(lineitems1(2), ")")
Id = CInt(lineitems2(0))
ActiveCell.Offset(row_number, 2).Value = LineItems(0)
ActiveCell.Offset(row_number2, 4).Value = Id
row_number = row_number + 1
row_number2 = row_number2 + 1
Loop

Close #1

    Next

End Sub