如何遍历目录并导出excel文件,工作簿的工作簿,逐页(VBA宏)的内容?

时间:2016-05-23 14:52:38

标签: excel vba excel-vba

我正在尝试将一些表从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

1 个答案:

答案 0 :(得分:0)

尝试这样的事情(未经测试):

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
相关问题