【发布时间】:2017-04-12 11:19:31
【问题描述】:
我在几个文件夹中有大量文本文件,我需要每个文本文件的第 14 行,我想知道是否有办法这样做?
目前我有以下脚本设置,其中我将文件夹目录输入到第一个工作表中的单元格 A19 中,这将返回目录中所有文件的文件路径。然后我想利用上述文件路径从每个文本文件的第 14 行获取信息。这是我的 到目前为止的代码:
Private Sub CommandButton1_Click()
'Call the recursive function
ListAllFiles ThisWorkbook.Sheets(1).Range("A19").Value, ThisWorkbook.Sheets(2).Cells(1, 1)
ReadTxtFiles
MsgBox "Task Completed"
End Sub
Private Sub ListAllFiles(root As String, targetCell As Range)
Dim objFSO As Object, objFolder As Object, objSubfolder As Object, objFile As Object
Dim i As Integer, Target_Path As String
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder(root)
'loops through each file in the directory and prints their names and path
For Each objFile In objFolder.Files
'print file name
targetCell.Value = objFile.Name
'print file path
targetCell.Offset(, 1).Value = objFile.Path
'print file type
'targetCell.Offset(, 2).Value = objFile.Type
'print file date created
'targetCell.Offset(, 3).Value = objFile.DateCreated
'print file date last accessed
'targetCell.Offset(, 4).Value = objFile.DateLastAccessed
'print file date last modified
'targetCell.Offset(, 5).Value = objFile.DateLastModified
Set targetCell = targetCell.Offset(1)
Next objFile
' Recursively call the function for subfolders
For Each objSubfolder In objFolder.SubFolders
ListAllFiles objSubfolder.Path, targetCell
Next objSubfolder
End Sub
Private Sub ReadTxtFiles()
'Dim start As Date
'start = Now
Dim oFSO As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim oFS As Object
'''''Assign the Workbook File Name along with its Path
'''''Change path of the Target File name
Dim v As Variant, filepath As String
For Each v In Worksheets("Sheet2").Columns("B").SpecialCells(xlCellTypeConstants)
filepath = v.Value
Debug.Print filepath
Dim arr(100000) As String
Dim i As Long
i = 0
If oFSO.FileExists(filepath) Then
On Error GoTo Err
Set oFS = oFSO.OpenTextFile(filepath)
Do While Not oFS.AtEndOfStream
arr(i) = oFS.ReadLine
i = i + 1
Loop
oFS.Close
Else
MsgBox "The file path is invalid.", vbCritical, vbNullString
Exit Sub
End If
这就是我卡住的地方。我想阅读每个文本文件并获取每个文件的第 14 行,仅此而已。
【问题讨论】: