我有几个子文件夹。每个都有文本文件。可以将文本文件分组到一个 excel 文件中,这样每个 excel 选项卡就有一个文件。我设计了代码来完成这项任务。
Option Explicit
Sub read_files()
Dim ReadData As String
Dim i As Double
Dim objfso As Object
Dim objfolder As Object
Dim obj_sub_folder As Object
Dim objfile As Object
Dim current_worksheet As Worksheet
Dim new_workbook As Workbook
Dim path As String
Dim filestream As Integer
Set objfso = CreateObject("Scripting.FilesystemObject")
Set objfolder = objfso.getfolder("Z:\test\")
Set new_workbook = Workbooks.Add
i = 1
For Each obj_sub_folder In objfolder.subfolders
i = 1
ReadData = ""
For Each objfile In obj_sub_folder.Files
Set current_worksheet = new_workbook.Worksheets.Add
current_worksheet.Name = objfile.Name
filestream = FreeFile()
path = "Z:\test\" & obj_sub_folder.Name & "\" & objfile.Name
Open path For Input As #filestream
Do Until EOF(filestream)
Input #filestream, ReadData
current_worksheet.Cells(i, 1).Value = ReadData
i = i + 1
Loop
Close filestream
Next
ActiveWorkbook.SaveAs "Z:\test\" & obj_sub_folder.Name
Next End Sub
但是,在遍历子文件夹时,宏会保存先前子文件夹中文件的数据,但我想保存来自特定子文件夹的文件中的数据。你能解释一下我的错误在哪里吗?
谢谢!
编辑
这是工作代码
Option Explicit
Sub run()
read_files ("Z:\test\")
End Sub
Sub read_files(path_to_folder As String)
Dim ReadData As String
Dim i As Double
Dim objfso As Object
Dim objfolder As Object
Dim obj_sub_folder As Object
Dim objfile As Object
Dim current_worksheet As Worksheet
Dim new_workbook As Workbook
Dim path As String
Dim filestream As Integer
Set objfso = CreateObject("Scripting.FilesystemObject")
Set objfolder = objfso.getfolder(path_to_folder)
i = 1
For Each obj_sub_folder In objfolder.subfolders
Set new_workbook = Workbooks.Add
For Each objfile In obj_sub_folder.Files
Set current_worksheet = new_workbook.Worksheets.Add
current_worksheet.Name = objfile.Name
filestream = FreeFile()
path = path_to_folder & obj_sub_folder.Name & "\" & objfile.Name
Open path For Input As #filestream
Do Until EOF(filestream)
Input #filestream, ReadData
current_worksheet.Cells(i, 1).Value = ReadData
i = i + 1
Loop
Close filestream
i = 1
Next
ActiveWorkbook.SaveAs path & obj_sub_folder.Name
ActiveWorkbook.Close
Next
结束子