1
我發現了一個適用於從指定目錄中的文本文件導入數據的宏。如何添加用於導入文本數據的文件的文件名
我沒有任何真正的VBA寫作經驗,但想知道是否有辦法採取下面的代碼,並添加能夠將文件的名稱從宏檢索到的數據從一列(如列A)。
我正在使用它來搜索特定數據的100多個日誌,並且能夠將這些日誌中的所有數據導入到excel中,這使得它非常簡單。現在我只需要一種方法來查看數據來自哪個文件。在此先感謝,我期待着學習新的東西。
宏:
Sub ReadFilesIntoActiveSheet()
Dim fso As FileSystemObject
Dim folder As folder
Dim file As file
Dim FileText As TextStream
Dim TextLine As String
Dim Items() As String
Dim i As Long
Dim cl As Range
' Get a FileSystem object
Set fso = New FileSystemObject
' get the directory you want
Set folder = fso.GetFolder("My File Path")
' set the starting point to write the data to
Set cl = ActiveSheet.Cells(1, 1)
' Loop thru all files in the folder
For Each file In folder.Files
' Open the file
Set FileText = file.OpenAsTextStream(ForReading)
' Read the file one line at a time
Do While Not FileText.AtEndOfStream
TextLine = FileText.ReadLine
' Parse the line into | delimited pieces
Items = Split(TextLine, "|")
' Put data on one row in active sheet
For i = 0 To UBound(Items)
cl.Offset(0, i).Value = Items(i)
Next
' Move to next row
Set cl = cl.Offset(1, 0)
Loop
' Clean up
FileText.Close
Next file
Set FileText = Nothing
Set file = Nothing
Set folder = Nothing
Set fso = Nothing
End Sub
感謝您的答覆。我沒有意識到這很容易。謝謝,問題解決了! –