Vba 如何添加用于导入文本数据的文件的文件名
我发现一个宏非常适合从指定目录中的文本文件导入数据 我没有任何使用VBA编写的实际经验,但我想知道是否有办法获取下面的代码,并添加将宏从中检索数据的文件名放入列(如a列)的功能 我使用它来搜索100多个日志中的特定数据,并且能够将这些日志中的所有数据导入excel,这使它变得非常简单。现在我只需要一种方法来查看数据来自哪个文件。提前谢谢,我期待着学习新的东西 宏:Vba 如何添加用于导入文本数据的文件的文件名,vba,excel,Vba,Excel,我发现一个宏非常适合从指定目录中的文本文件导入数据 我没有任何使用VBA编写的实际经验,但我想知道是否有办法获取下面的代码,并添加将宏从中检索数据的文件名放入列(如a列)的功能 我使用它来搜索100多个日志中的特定数据,并且能够将这些日志中的所有数据导入excel,这使它变得非常简单。现在我只需要一种方法来查看数据来自哪个文件。提前谢谢,我期待着学习新的东西 宏: Sub ReadFilesIntoActiveSheet() Dim fso As FileSystemObject
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
谢谢你的回复。我没有意识到这是如此容易。谢谢,问题解决了!
cl.value = file.Name
' Put data on one row in active sheet
For i = 0 To UBound(Items)
cl.Offset(0, i+1).Value = Items(i)
Next