根据电子表格中的数据生成文件夹和文件

时间:2016-03-23 22:37:43

标签: excel vba excel-vba

为工作解决方案提供亚马逊礼品卡

我有一个1200个左右的条目的电子表格,每个条目都在自己的行中。我正在尝试编写一个宏来为每个条目创建一个文件夹,并在这些文件夹中有一个单独的excel文件,其中包含来自其他列的其他信息。

列A包含所需的文件夹名称,列B包含所需的Excel文件名。每个excel文件应包含主文件的单元格B1:O1的标题以及条目行的B:O列的值。

这可以通过宏或其他方式完成吗?我正在使用Mac,如果绝对必要,我可以找到一台Windows机器。

下面的sub是我到目前为止所做的,但是在尝试运行时会抛出错误。

Sub MakeFiles()

    Dim lastrow As Long, i As Long
    Dim rootPath As String, newDir As String
    Dim cSheet As Worksheet, pSheet As Worksheet

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Application.Calculation = xlCalculationManual

    Set cSheet = ThisWorkbook.ActiveSheet

    lastrow = Cells(Rows.Count, 1).End(xlUp).Row
    rootPath = "C:\Excel\"    'MUST INCLUDE \ AT END

    For i = 2 To lastrow

        Application.StatusBar = Cells(i, 1)

        'CREATES FOLDER
        newDir = rootPath & Cells(i, 1)
        MkDir newDir

        'MAKE A NEW WORKBOOK
        Workbooks.Add

        Set pSheet = ActiveWorkbook.ActiveSheet

        With cSheet

            'COPY HEADER
            Range(.Cells(1, 2), .Cells(1, 15)).Copy Destination:=pSheet.[A1]

            'COPY THAT ROWS DATA
            Range(.Cells(i, 2), .Cells(i, 15)).Copy Destination:=pSheet.[A2]

            'SAVES AS THE NAME IN COLUMN A
            pSheet.SaveAs newDir & "\" & Cells(i, 1) &".xlsx"

            'CLOSES THE BOOK AND MOVES ON
            pSheet.Parent.Close False

            'GO BACK TO FIRST SHEET
            cSheet.Activate

        End With

    Next

    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
    Application.StatusBar = False

End Sub

0 个答案:

没有答案