2009-10-19 03:49:07 +0000 2009-10-19 03:49:07 +0000
9
9

在Excel 2007中,我可以根据一列将一个电子表格分割成多个文件吗?

在Excel中,有没有一种方法可以根据单列的内容,将一个大文件分割成一系列小文件?

例如:我有一个所有销售代表的销售数据文件。我需要给他们发送一个文件,让他们进行修改并发送回来,但我不想给他们每个人发送整个文件(因为我不想让他们改变彼此的数据)。这个文件看起来像这样。

salesdata.xls

RepName Customer ContactEmail
Adam Cust1 admin@cust1.com
Adam Cust2 admin@cust2.com
Bob Cust3 blah@cust3.com
etc...

从中我需要:

salesdata_Adam.xls

RepName Customer ContactEmail
Adam Cust1 admin@cust1.com
Adam Cust2 admin@cust2.com

salesdata_Bob.xls

Bob Cust3 blah@cust3.com

Excel 2007有什么内置的东西可以自动完成这些操作吗? 或者我应该使用VBA?

答案 (5)

8
8
8
2012-03-05 04:10:01 +0000

为了方便后人,这里还有一个宏来解决这个问题。

这个宏会自上而下地检查指定的列,每当遇到一个新的值时,就会分割到一个新的文件中。空白或重复的值会被保留在一起(以及总的行数),但你的列值必须是排序的或唯一的。我主要是为了配合PivotTables布局而设计的(一旦转换为值)。

所以就像现在这样,没有必要修改代码或准备一个命名的范围。宏开始时提示用户要处理的列,以及开始的行号–也就是跳过标题,然后从那里开始。

当确定一个部分时,不是将这些值复制到另一个工作表中,而是将整个工作表复制到一个新的工作簿中,并删除该部分下面和上面的所有行。这允许保留任何打印设置、条件格式、图表或其他任何你可能有的东西,以及保留每个分割文件中的标题,这在分发这些文件时很有用。

文件被保存在一个以单元格值为文件名的子文件夹中。我还没有在各种文件上进行广泛的测试,但它在我的样本文件上工作。欢迎试用它,如果你有问题,请告诉我。

该宏可以保存为excel插件(xlam),在ribbon/quickaccess工具栏按钮上添加一个按钮,方便访问。

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
6
6
6
2009-10-19 03:53:42 +0000

据我所知,没有什么比宏更有效的方法来分割你的数据,并自动为你保存到一组文件中。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

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

2
2
2
2009-10-19 03:59:17 +0000

如果有人回答出了正确的方法,而且是快速的方法,请忽略这个答案。

我个人发现自己在使用Excel的时候,花了很多时间(有时是几个小时)去寻找一个复杂的方法来做某事,或者是一个可以做所有事情的公式,而我再也不会使用它了……结果发现如果我坐下来手动完成任务,只需要花很少的时间。


如果你只有少数人,我建议你做的是简单地高亮所有数据,进入数据选项卡,然后点击排序按钮。

然后你可以选择用什么列来排序,在你的例子中,你想用Repname,然后复制并粘贴到各个文件。

我相信使用VBA或其他工具,你可能会想出一个解决方案,但事实是,你将会看到几个小时的工作,而使用上面的方法应该可以让你在短时间内完成。

另外,我认为你可以在sharepoint+excel服务上做这种事情,但这是一种超乎寻常的解决方法,对于这种事情。

1
1
1
2009-10-19 20:13:28 +0000

好了,这里是VBA的第一刀。你可以这样调用它。

SplitIntoFiles Range("A1:N1"), Range("A2:N2"), Range("B2"), "Split File - "

其中A1: N1是你的头行, A2: N2是你数据的第一行, B2是你的预排序键列的第一个单元格. 最后一个参数是文件名前缀。在保存之前,键值将被附加到这里。

声明:这段代码很恶心。

Option Explicit
Public Sub SplitIntoFiles(headerRange As Range, startRange As Range, keyCell As Range, filenameBase As String)

    ' assume the keyCell column is already sorted

    ' start a new workbook
    Dim wb As Workbook
    Dim ws As Worksheet

    Set wb = Application.Workbooks.Add
    Set ws = wb.ActiveSheet

    Dim destRange As Range
    Set destRange = ws.Range("A1")

    ' copy header
    headerRange.Copy destRange
    Set destRange = destRange.Offset(headerRange.Rows.Count)

    Dim keyValue As Variant
    keyValue = ""

    While keyCell.Value <> ""

        ' if we've got a new key, save the file and start a new one
        If (keyValue <> keyCell.Value) Then
        If keyValue <> "" Then
            'TODO: remove non-filename chars from keyValue
            wb.SaveAs filenameBase & CStr(keyValue)
            wb.Close False
            Set wb = Application.Workbooks.Add
            Set ws = wb.ActiveSheet
            Set destRange = ws.Range("A1")

            ' copy header
            headerRange.Copy destRange
            Set destRange = destRange.Offset(headerRange.Rows.Count)

            End If
        End If

        keyValue = keyCell.Value

        ' copy the contents of this row to the new sheet
        startRange.Copy destRange

        Set keyCell = keyCell.Offset(1)
        Set destRange = destRange.Offset(1)
        Set startRange = startRange.Offset(1)
    Wend

    ' save residual
    'TODO: remove non-filename chars from keyValue
    wb.SaveAs filenameBase & CStr(keyValue)
    wb.Close

End Sub
-2
-2
-2
2012-12-11 08:32:17 +0000

我按名字排序,然后把信息直接粘贴到第二张Excel表格中,就是你要发的那张。Excel只粘贴你看到的行,不也是隐藏的行。我还保护了所有的单元格,除了我要他们更新的单元格,呵呵。