代码改进需要

时间:2017-05-09 09:23:03

标签: excel vba excel-vba export

据我所知,它现在只是多次复制active.sheet而不是循环。

我想要实现的目标是让宏运行并将每个工作表转换为.csv。该.csv的文件名将是工作表名称,由另一个宏决定,而不是在流程中先前运行。

正如我之前所说,关于如何绕过的任何想法。我对代码比较陌生,因此我会问。

Sub Export_Sub_Xpath()     '     ' Export_Sub_Xpath宏     '

    Dim i As Integer
    Dim WS_Count As Integer
    Dim ws As Worksheet

    WS_Count = ActiveWorkbook.Worksheets.Count
    For i = 1 To WS_Count



    Set ws = ThisWorkbook.Worksheets(i)
    PathName = "" & ActiveWorkbook.Path & "\" & ws.Name & ".csv"
    Columns("A:B").Select
    Range("B3000").Activate
    Selection.Copy
    PathName = "" & ActiveWorkbook.Path & "\" & ws.Name & ".csv"
    Workbooks.Add
    ActiveSheet.Paste
    Application.CutCopyMode = False
    'ActiveWorkbook.SaveAs PathName = "" & ActiveWorkbook.Path & "\" & ws.Name & ".csv"
    ActiveWorkbook.SaveAs Filename:=PathName, _
        FileFormat:=xlCSV, CreateBackup:=False
    ActiveWorkbook.Close

Next i

End Sub

1 个答案:

答案 0 :(得分:0)

在复制和保存之前,您忘记激活每张纸。试试这个:

Sub Export_Sub_Xpath() ' ' Export_Sub_Xpath Macro '
    Dim i As Integer
    Dim WS_Count As Integer
    Dim ws As Worksheet

    WS_Count = ThisWorkbook.Worksheets.Count

    For i = 1 To WS_Count
            Set ws = ThisWorkbook.Worksheets(i)
            PathName = "" & ThisWorkbook.Path & "\" & ws.Name & ".csv"
            ThisWorkbook.Worksheets(i).Activate  ' You forgeot to Activate Each Sheet before saving
            Columns("A:B").Select
            Range("B3000").Activate                 
            Selection.Copy
            Workbooks.Add
            ActiveSheet.Paste
            Application.CutCopyMode = False
            ActiveWorkbook.SaveAs Filename:=PathName, _
                FileFormat:=xlCSV, CreateBackup:=False
            ActiveWorkbook.Close

Next i

End Sub