简体   繁体   English

使用Excel VBA将单个工作簿拆分为包含多个工作表的多个工作簿

[英]Split a single workbook into multiple workbooks containing multiple worksheets using Excel VBA

I have a workbook with single worksheet as given below. 我有一个带有单个工作表的工作簿,如下所示。 在此处输入图片说明

I want to split it into many workbooks containing many worksheets according to the values in it. 我想根据其中的值将其拆分为包含许多工作表的许多工作簿。 I want to make 'n' number of workbooks according to 'n' unique values of column 1 as in the picture. 我想根据图片中第1列的“ n”个唯一值来制作“ n”个工作簿。 And I want to make 'm' worksheets according to 'm' unique values of column 2 as in the picture. 我想根据图片中第2列的“ m”个唯一值制作“ m”个工作表。 在此处输入图片说明在此处输入图片说明

Each worksheet contains values as in the picture. 每个工作表都包含图片中的值。 Actually I want to make a chart with 3 series. 实际上,我想制作一个包含3个系列的图表。 So I have to make data table as in the picture with columns 'levels', 'chart_vlaue_1', 'chart_vlaue_2', 'chart_vlaue_3' in each worksheet. 因此,我必须像在图片中那样在每个工作表中使用“级别”,“ chart_vlaue_1”,“ chart_vlaue_2”,“ chart_vlaue_3”列制作数据表。 Also I want to generate charts in each of the worksheet. 我也想在每个工作表中生成图表。 Please help me a create a sample chart. 请帮助我创建一个示例图表。 I will work on it. 我会努力的。 Please help me. 请帮我。

Try below, below should sort your data into the correct sheets/workbooks and create you a chart for each sheet. 请尝试以下操作,以下应将数据分类到正确的工作表/工作簿中,并为每个工作表创建一个图表。 f_Path is the file path of where you will save these files. f_Path是将这些文件保存到的文件路径。 if the files already exist the code will SKIP THESE 如果文件已经存在,则代码将跳过这些

Sub main()
Dim f_Path
f_Path = "C:\" 'Filepath to save files to

With ActiveSheet 'run on activesheet
    If .Cells(2, 1).Value <> "" Then 'if A2 not blank
        For Each cell In .Range("A2:" & .Range("A2").End(xlDown).Address)
            If Dir(f_Path & cell.Value & ".xls") <> "" Then
                'exists
                If IsWorkBookOpen(f_Path & cell.Value & ".xls") Then
                     'open
                Else
                    GoTo Skipper 'not open
                End If
                Workbooks(cell.Value & ".xls").Activate

                On Error Resume Next
                Sheets(cell.Offset(0, 1).Value).Select
                If Err.Number <> 0 Then
                    Worksheets.Add().Name = cell.Offset(0, 1).Value
                End If
                On Error GoTo 0
                lastrow = ActiveSheet.Range("A1").End(xlDown).Row - 1
                If lastrow = 1048575 Then 'First time
                    With ActiveSheet
                        .Range("A1").Value = "Levels"
                        .Range("B1").Value = "Chart_Value1"
                        .Range("C1").Value = "Chart_Value2"
                        .Range("D1").Value = "Chart_Value3"
                        .Range("A2").Value = cell.Offset(0, 2).Value
                        .Range("B2").Value = cell.Offset(0, 3).Value
                        .Range("C2").Value = cell.Offset(0, 5).Value
                        .Range("D2").Value = cell.Offset(0, 7).Value
                    End With
                Else
                    With ActiveSheet
                        .Range("A2").Offset(0 + lastrow, 0).Value = cell.Offset(0, 2).Value
                        .Range("B2").Offset(0 + lastrow, 0).Value = cell.Offset(0, 3).Value
                        .Range("C2").Offset(0 + lastrow, 0).Value = cell.Offset(0, 5).Value
                        .Range("D2").Offset(0 + lastrow, 0).Value = cell.Offset(0, 7).Value
                    End With
                End If
                ActiveWorkbook.Save
            Else
                'does not
                Set wb = Workbooks.Add(xlWBATWorksheet)
                With ActiveSheet
                    .Name = cell.Offset(0, 1).Value
                    .Range("A1").Value = "Levels"
                    .Range("B1").Value = "Chart_Value1"
                    .Range("C1").Value = "Chart_Value2"
                    .Range("D1").Value = "Chart_Value3"
                    .Range("A2").Value = cell.Offset(0, 2).Value
                    .Range("B2").Value = cell.Offset(0, 3).Value
                    .Range("C2").Value = cell.Offset(0, 5).Value
                    .Range("D2").Value = cell.Offset(0, 7).Value
                End With
                ActiveWorkbook.SaveAs f_Path & cell.Value & ".xls", 56
            End If
Skipper:
        Next
    End If
End With

For Each wb In Workbooks
    If ThisWorkbook.Name <> wb.Name Then
        For Each ws In wb.Worksheets
            With ws
                Set Rng = ws.UsedRange
                ws.Shapes.AddChart
            End With
        Next
        wb.Close True
    End If
Next

End Sub

Function IsWorkBookOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0:    IsWorkBookOpen = False
    Case 70:   IsWorkBookOpen = True
    Case Else: Error ErrNo
    End Select
End Function

The following code will parse the data in first two columns create workbooks for each unique cell value from first column and sheet for each unique cell value from second column. 下面的代码将解析前两列中的数据,为第一列中的每个唯一单元格值创建工作簿,为第二列中的每个唯一单元格值创建工作表。 It finally adds charts of type xlColumnClustered and saves and closes all the new books. 最后,它将添加类型为xlColumnClustered图表,并保存和关闭所有新书。 Source data can be un-sorted . 源数据可以un-sorted

Important : change the constants TargetPath and/or DataBookName, DataSheetName according to your conditions. 重要提示根据您的条件更改常数TargetPath和/或DataBookName, DataSheetName

Option Explicit

' ---------------------------------------------------------------------------------------
' Results will be saved 'TargetPath' path. This path must be changed according to your PC
' Change this path:
Private Const TargetPath As String = "C:\Temp\Abdul_Shiyas\Results\"
' ---------------------------------------------------------------------------------------

' ---------------------------------------------------------------------------------------
' Expected data are contain in sheet named "Data" in wokbook with the name "Data.xlsx"
' This names can be changed according to your wokbook with data.
Private Const DataBookName As String = "Data.xlsx"
Private Const DataSheetName As String = "Data"
' ---------------------------------------------------------------------------------------

Private sourceBook As Workbook
Private sht As Worksheet
Private book As Workbook
Private books As Collection
Private header As Range
Private data As Range
Private criteria As Range
Private criteriaRow As Range
Private bookName As String
Private sheetName As String
Private newChart As Shape

Public Sub ParseToWorkbooks()

    ' Important:
    ' Data are expected to begin in cell "A1" and should not contain any blank rows or blank columns
    Set sourceBook = Workbooks(DataBookName)
    Set data = sourceBook.Worksheets(DataSheetName).Range("A1").CurrentRegion
    Set header = data.Rows(1)
    Set data = data.Offset(1, 0).Resize(data.Rows.Count - 1, data.Columns.Count)
    Set criteria = data.Resize(data.Rows.Count, 2)
    Set header = header.Offset(0, criteria.Columns.Count).Resize(1, header.Columns.Count - criteria.Columns.Count)
    Set books = New Collection

    For Each criteriaRow In criteria.Rows
        bookName = Trim(criteriaRow.Cells(1))
        sheetName = Trim(criteriaRow.Cells(2))

        ' get the book first
        Set book = Nothing
        On Error Resume Next
        Set book = books(bookName)
        On Error GoTo 0

        If book Is Nothing Then
            Set book = Workbooks.Add
            Application.DisplayAlerts = False
            book.SaveAs Filename:=TargetPath & bookName
            Application.DisplayAlerts = True
            books.Add book, bookName
        End If

        ' get the sheet then
        Set sht = Nothing
        On Error Resume Next
        Set sht = book.Worksheets(sheetName)
        On Error GoTo 0

        If sht Is Nothing Then
            Set sht = book.Worksheets.Add
            sht.Name = sheetName
            header.Copy Destination:=sht.Range("A1")
        End If

        ' paste data to the sheet
        criteriaRow.Cells(2).Offset(0, 1).Resize(1, data.Columns.Count - criteria.Columns.Count).Copy _
            Destination:=sht.Cells(sht.Rows.Count, 1).End(xlUp).Offset(1, 0)

    Next criteriaRow

    ' finally and chart, save and close each new book
    For Each book In books
        For Each sht In book.Worksheets
            If sht.Range("A1").Value <> "" Then
                Set newChart = sht.Shapes.AddChart
                newChart.Chart.SetSourceData Source:=sht.Range("A1").CurrentRegion
                newChart.Chart.ChartType = xlColumnClustered
            End If
        Next sht

        book.Close True
    Next book
End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将数据从工作簿中的多个工作表复制到单独工作簿中的不同工作表-VBA Excel - Copying Data from Multiple Worksheets in Workbooks to Differing Worksheets in Separate Workbook - VBA Excel 使用 vba 在多个工作表和工作簿中查找 excel 中的值 - find a value in excel across multiple worksheets and workbooks using vba 从多个工作簿复制到单个工作簿 Excel VBA - Copying from multiple workbooks to single workbook Excel VBA VBA:将多个工作簿(具有多个工作表)中的特定单元格复制到单个工作簿 - VBA : Copy Specific cells from Multiple Workbooks(having Multiple Worksheets) to a single WorkBook 通过将多个 excel 工作簿中的多个工作表组合到一个工作簿中。 R - Combining multiple worksheets from multiple excel workbooks into a single workbook via. R 使用PowerShell将多个Excel工作表从多个工作簿复制到新工作簿 - Copy multiple Excel worksheets from multiple workbooks to a new workbook using PowerShell 使用VBA在工作簿中循环浏览多个Excel工作表 - Loop through multiple excel worksheets within a workbook using VBA Excel VBA:将多个工作簿合并为一个工作簿 - Excel VBA: Combine multiple workbooks into one workbook 将具有特定名称的Excel工作表从多个工作簿复制到新工作簿 - Copy Excel Worksheets with Specific Name from Multiple Workbooks to New Workbook 取消保护Excel工作表并将其从多个工作簿追加到新工作簿 - Unprotect and Append Excel Worksheets from Multiple Workbooks to a New Workbook
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM