[英]How to loop through directory and export content of excel files, workbook by workbook, sheet by sheet (VBA Macros)?
I am trying to export some tables from excel workbooks to txt files. 我正在尝试将一些表格从excel工作簿导出到txt文件。 I have managed to do this for a workbook whilst I have it open. 当我打开工作簿时,我已经设法做到这一点。 My code will loop through the sheets of a workbook I have open, and export the content to txt files (different file for each sheet). 我的代码将遍历我打开的工作簿的工作表,并将内容导出到txt文件(每个工作表的文件都不同)。 I need it to loop through a directory of .xlsx files and do the same without any manual labor. 我需要它循环遍历.xlsx文件的目录,并且无需任何手工操作即可执行此操作。 Can anyone help? 有人可以帮忙吗?
Below is my code: 下面是我的代码:
Sub Exportation()
Dim directory As String
Dim WS_Count As Integer, myFile As String, x As Integer
Dim rng As Range, cellValue As Variant, i As Integer, j As Integer
directory = "C:\Users\Mike\Desktop\Testing\" ' The starting directory
Dim fso, newFile, folder, files
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(directory)
Set files = folder.files
For Each file In files
WS_Count = ActiveWorkbook.Worksheets.Count
For x = 1 To WS_Count
myFile = "C:\Users\mohamednuri.beitelma\Desktop\" & Sheets(x).Name & ".txt"
'Set rng = Selection
Set rng = Sheets(x).Range("A1").CurrentRegion
Open myFile For Output As #1
cnt = Sheets(x).Cells.SpecialCells(xlCellTypeLastCell).Row
For i = 1 To rng.Rows.Count
For j = 1 To rng.Columns.Count
cellValue = rng.Cells(i, j).Value
If j = rng.Columns.Count Then
Print #1, cellValue
Else
Print #1, cellValue & "|",
End If
Next j
Next i
Print #1, cnt & " -- " & DateTime.Now
Close #1
Next x
Next
End Sub
Try something like this (untested): 尝试以下操作(未经测试):
Sub Exportation()
Dim directory As String
Dim wb As Workbook
Dim ws as worksheet
Dim WS_Count As Integer, myFile As String, x As Integer
Dim rng As Range, cellValue As Variant, i As Integer, j As Integer
directory = "C:\Users\Mike\Desktop\Testing\" ' The starting directory
Dim fso, newFile, folder, files
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(directory)
Set files = folder.files
For Each file In files
set wb = workbooks.open(filename:=file.path)
WS_Count = wb.Worksheets.Count
For x = 1 To WS_Count
myFile = "C:\Users\mohamednuri.beitelma\Desktop\" & Sheets(x).Name & ".txt"
'Set rng = Selection
Set rng = wb.Sheets(x).Range("A1").CurrentRegion
Open myFile For Output As #1
cnt = wb.Sheets(x).Cells.SpecialCells(xlCellTypeLastCell).Row
For i = 1 To rng.Rows.Count
For j = 1 To rng.Columns.Count
cellValue = rng.Cells(i, j).Value
If j = rng.Columns.Count Then
Print #1, cellValue
Else
Print #1, cellValue & "|",
End If
Next j
Next i
Print #1, cnt & " -- " & DateTime.Now
Close #1
Next x
Next
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.