我可以根据 Excel 2007 中的列将电子表格拆分为多个文件吗?

geo*_*tnz 9 microsoft-excel-2007 microsoft-excel

Excel 中有没有办法根据单列的内容将大文件拆分为一系列较小的文件?

例如:我有一个所有销售代表的销售数据文件。我需要向他们发送一个文件以进行更正并发回,但我不想将整个文件发送给他们每个人(因为我不希望他们更改彼此的数据)。该文件如下所示:

销售数据.xls

RepName          Customer        ContactEmail
Adam             Cust1           admin@cust1.com
Adam             Cust2           admin@cust2.com
Bob              Cust3           blah@cust3.com
etc...
Run Code Online (Sandbox Code Playgroud)

为此,我需要:

销售数据_亚当.xls

RepName          Customer        ContactEmail
Adam             Cust1           admin@cust1.com
Adam             Cust2           admin@cust2.com
Run Code Online (Sandbox Code Playgroud)

和 salesdata_Bob.xls

Bob              Cust3           blah@cust3.com
Run Code Online (Sandbox Code Playgroud)

Excel 2007 中是否有任何内置功能可以自动执行此操作,还是应该打破 VBA?

mto*_*one 8

对于后代,这里还有另一个宏来解决这个问题。

此宏将遍历指定的列,自上而下,并在遇到新值时拆分为新文件。空白或重复值保持在一起(以及总行数),但您的列值必须排序或唯一。我主要将它设计为与数据透视表布局一起使用(一旦转换为 values)。

因此,无需修改代码或准备命名范围。宏首先提示用户输入要处理的列以及开始的行号 - 即跳过标题,然后从那里开始。

当识别出一个部分时,不是将这些值复制到另一个工作表,而是将整个工作表复制到一个新工作簿,并删除该部分下方和上方的所有行。这允许保留任何打印设置、条件格式、图表或您可能拥有的任何其他内容,以及在每个拆分文件中保留标题,这在分发这些文件时非常有用。

文件保存在 \Split\ 子文件夹中,单元格值作为文件名。我还没有对各种文档进行广泛的测试,但它适用于我的示例文件。随意尝试一下,如果您有问题,请告诉我。

宏可以保存为 excel 加载项 (xlam),以便在功能区/快速访问工具栏按钮上添加一个按钮,以便于访问。

Public Sub SplitToFiles()

' MACRO SplitToFiles
' Last update: 2019-05-28
' Author: mtone
' Version 1.2
' Description:
' Loops through a specified column, and split each distinct values into a separate file by making a copy and deleting rows below and above
'
' Note: Values in the column should be unique or sorted.
'
' The following cells are ignored when delimiting sections:
' - blank cells, or containing spaces only
' - same value repeated
' - cells containing "total"
'
' Files are saved in a "Split" subfolder from the location of the source workbook, and named after the section name.

Dim osh As Worksheet ' Original sheet
Dim iRow As Long ' Cursors
Dim iCol As Long
Dim iFirstRow As Long ' Constant
Dim iTotalRows As Long ' Constant
Dim iStartRow As Long ' Section delimiters
Dim iStopRow As Long
Dim sSectionName As String ' Section name (and filename)
Dim rCell As Range ' current cell
Dim owb As Workbook ' Original workbook
Dim sFilePath As String ' Constant
Dim iCount As Integer ' # of documents created

iCol = Application.InputBox("Enter the column number used for splitting", "Select column", 2, , , , , 1)
iRow = Application.InputBox("Enter the starting row number (to skip header)", "Select row", 2, , , , , 1)
iFirstRow = iRow

Set osh = Application.ActiveSheet
Set owb = Application.ActiveWorkbook
iTotalRows = osh.UsedRange.Rows.Count
sFilePath = Application.ActiveWorkbook.Path

If Dir(sFilePath + "\Split", vbDirectory) = "" Then
    MkDir sFilePath + "\Split"
End If

'Turn Off Screen Updating  Events
Application.EnableEvents = False
Application.ScreenUpdating = False

Do
    ' Get cell at cursor
    Set rCell = osh.Cells(iRow, iCol)
    sCell = Replace(rCell.Text, " ", "")

    If sCell = "" Or (rCell.Text = sSectionName And iStartRow <> 0) Or InStr(1, rCell.Text, "total", vbTextCompare) <> 0 Then
        ' Skip condition met
    Else
        ' Found new section
        If iStartRow = 0 Then
            ' StartRow delimiter not set, meaning beginning a new section
            sSectionName = rCell.Text
            iStartRow = iRow
        Else
            ' StartRow delimiter set, meaning we reached the end of a section
            iStopRow = iRow - 1

            ' Pass variables to a separate sub to create and save the new worksheet
            CopySheet osh, iFirstRow, iStartRow, iStopRow, iTotalRows, sFilePath, sSectionName, owb.fileFormat
            iCount = iCount + 1

            ' Reset section delimiters
            iStartRow = 0
            iStopRow = 0

            ' Ready to continue loop
            iRow = iRow - 1
        End If
    End If

    ' Continue until last row is reached
    If iRow < iTotalRows Then
            iRow = iRow + 1
    Else
        ' Finished. Save the last section
        iStopRow = iRow
        CopySheet osh, iFirstRow, iStartRow, iStopRow, iTotalRows, sFilePath, sSectionName, owb.fileFormat
        iCount = iCount + 1

        ' Exit
        Exit Do
    End If
Loop

'Turn On Screen Updating  Events
Application.ScreenUpdating = True
Application.EnableEvents = True

MsgBox Str(iCount) + " documents saved in " + sFilePath


End Sub

Public Sub DeleteRows(targetSheet As Worksheet, RowFrom As Long, RowTo As Long)

Dim rngRange As Range
Set rngRange = Range(targetSheet.Cells(RowFrom, 1), targetSheet.Cells(RowTo, 1)).EntireRow
rngRange.Select
rngRange.Delete

End Sub


Public Sub CopySheet(osh As Worksheet, iFirstRow As Long, iStartRow As Long, iStopRow As Long, iTotalRows As Long, sFilePath As String, sSectionName As String, fileFormat As XlFileFormat)
     Dim ash As Worksheet ' Copied sheet
     Dim awb As Workbook ' New workbook

     ' Copy book
     osh.Copy
     Set ash = Application.ActiveSheet

     ' Delete Rows after section
     If iTotalRows > iStopRow Then
         DeleteRows ash, iStopRow + 1, iTotalRows
     End If

     ' Delete Rows before section
     If iStartRow > iFirstRow Then
         DeleteRows ash, iFirstRow, iStartRow - 1
     End If

     ' Select left-topmost cell
     ash.Cells(1, 1).Select

     ' Clean up a few characters to prevent invalid filename
     sSectionName = Replace(sSectionName, "/", " ")
     sSectionName = Replace(sSectionName, "\", " ")
     sSectionName = Replace(sSectionName, ":", " ")
     sSectionName = Replace(sSectionName, "=", " ")
     sSectionName = Replace(sSectionName, "*", " ")
     sSectionName = Replace(sSectionName, ".", " ")
     sSectionName = Replace(sSectionName, "?", " ")
     sSectionName = Strings.Trim(sSectionName)

     ' Save in same format as original workbook
     ash.SaveAs sFilePath + "\Split\" + sSectionName, fileFormat

     ' Close
     Set awb = ash.Parent
     awb.Close SaveChanges:=False
End Sub
Run Code Online (Sandbox Code Playgroud)


Dav*_*llo 6

据我所知,只有一个宏可以拆分您的数据并自动将其保存到一组文件中。VBA 可能更容易。

更新 我实施了我的建议。它遍历命名范围“RepList”中定义的所有名称。命名范围是形式为 =OFFSET(Names!$A$2,0,0,COUNTA(Names!$A:$A)-1,1) 的动态命名范围

模块如下。

Option Explicit

'Split sales data into separate columns baed on the names defined in
'a Sales Rep List on the 'Names' sheet.
Sub SplitSalesData()
    Dim wb As Workbook
    Dim p As Range

    Application.ScreenUpdating = False

    For Each p In Sheets("Names").Range("RepList")
        Workbooks.Add
        Set wb = ActiveWorkbook
        ThisWorkbook.Activate

        WritePersonToWorkbook wb, p.Value

        wb.SaveAs ThisWorkbook.Path & "\salesdata_" & p.Value
        wb.Close
    Next p
    Application.ScreenUpdating = True
    Set wb = Nothing
End Sub

'Writes all the sales data rows belonging to a Person
'to the first sheet in the named SalesWB.
Sub WritePersonToWorkbook(ByVal SalesWB As Workbook, _
                          ByVal Person As String)
    Dim rw As Range
    Dim personRows As Range     'Stores all of the rows found
                                'containing Person in column 1
    For Each rw In UsedRange.Rows
        If Person = rw.Cells(1, 1) Then
            If personRows Is Nothing Then
                Set personRows = rw
            Else
                Set personRows = Union(personRows, rw)
            End If
        End If
    Next rw

    personRows.Copy SalesWB.Sheets(1).Cells(1, 1)
    Ser personRows = Nothing
End Sub
Run Code Online (Sandbox Code Playgroud)

此工作簿包含代码和命名范围。该代码是“销售数据”表的一部分。