指定したディレクトリのテキストファイルからデータをインポートするのに最適なマクロを見つけました。
私は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