使用vba从多个文件中提取字符串

时间:2015-04-20 13:28:31

标签: vba text extract

我需要从文件夹中的一组文本文件中提取数据。我试了几次都没有成功,我希望有人可以帮助我。

我必须阅读的所有文件都在文件夹C:/test内。我需要从文本文件中提取的数据位于关键字之后。 数据应放在excel文件中(从不同单元格内的单个文本文件复制的每个数据)。

我尝试使用此宏,但它不起作用:

Dim myFile As String, myFolder As String, text As String, textline As String, originatorName As String, entryDescription As String, amount As Long

Sub Button1_Click()

Dim fs, f, f1, fc

Dim cella

cella = A2

    'Add column headers

Range("A1").Value = "Brightness"

Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFolder("C:\prova")
Set fc = f.Files
For Each f1 In fc
    If InStr(1, f1.Name, ".txt") Then

'Open file
Open f1 For Input As #1

Do Until EOF(1)
    Line Input #1, textline
    text = text & textline
Loop

'Close file
Close #1

ReadBRTLuminance = InStr(text, "Read BRT Luminance")

ActiveCell.Offset(cella, 1).Value = Mid(text, ReadBRTLuminance + 31, 9)
cella = cella + 1

End If

Next


End Sub

我写了一个宏来从单个文件中提取我需要的数据(并且工作正常)。关键字是Read BRT Luminance,宏是:

Dim myFile As String,myFolder As String,text As String,textline As String,originatorName As String,entryDescription As String,amount As Long

Sub Button1_Click()

'Add column headers
Range("A1").Value = "Brightness"


'Show open file dialog box
myFile = Application.GetOpenFilename()

'Open file
Open myFile For Input As #1

Do Until EOF(1)
    Line Input #1, textline
    text = text & textline
Loop

'Close file
Close #1

ReadBRTLuminance = InStr(text, "Read BRT Luminance")

Range("A2").Value = Mid(text, ReadBRTLuminance + 31, 9)

End Sub

1 个答案:

答案 0 :(得分:2)

您没有清除文件之间的文本值,因此您总是从第一个文件中获取值...

相关问题