【发布时间】:2015-04-20 13:28:31
【问题描述】:
我需要从文件夹内的一组文本文件中提取数据。我试了好几次都没有成功,希望有人能帮帮我。
我必须阅读的所有文件都在文件夹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,宏是:
将 myFile 作为字符串,myFolder 作为字符串,文本作为字符串,文本行作为字符串,originatorName 作为字符串,entryDescription 作为字符串,金额作为 Long
子按钮1_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)
结束子
【问题讨论】:
-
您是否将文件夹从
C:\prova更改为C:\test? -
Dim cella,cella = A2和cella = cella + 1对我来说确实很奇怪,因为你在偏移量中使用它,所以它应该是一个整数,如果你添加到许多文件,也许长。试试Dim cella as Integer和cella = 2当你发布一个不起作用的代码时,请说明你的错误信息和它发生的行。 -
是的,我已将文件夹更改为 C:/prova。我没有收到任何错误消息。我的文件夹中有 20 个文件,我的脚本似乎读取同一个文件 20 次,因为我获得了一个在 20 个不同单元格中重复 20 次相同值的文件