[英]How to loop through directory and export content of excel files, workbook by workbook, sheet by sheet (VBA Macros)?
我正在嘗試將一些表格從excel工作簿導出到txt文件。 當我打開工作簿時,我已經設法做到這一點。 我的代碼將遍歷我打開的工作簿的工作表,並將內容導出到txt文件(每個工作表的文件都不同)。 我需要它循環遍歷.xlsx文件的目錄,並且無需任何手工操作即可執行此操作。 有人可以幫忙嗎?
下面是我的代碼:
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
嘗試以下操作(未經測試):
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.