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

¿Puedo dividir una hoja de cálculo en varios archivos en función de una columna en Excel 2007?

Advertisement

¿Existe alguna manera en Excel de dividir un archivo grande en una serie de archivos más pequeños, basándose en el contenido de una sola columna?

por ejemplo: Tengo un archivo de datos de ventas para todos los representantes de ventas. Necesito enviarles un archivo para que hagan correcciones y lo devuelvan, pero no quiero enviar a cada uno de ellos el archivo completo (porque no quiero que cambien los datos de cada uno). El archivo es algo así

salesdata.xls

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

de esto necesito:

salesdata_Adam.xls

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

y salesdata_Bob.xls

Bob Cust3 blah@cust3.com

¿Existe algo incorporado en Excel 2007 para hacer esto automáticamente, o tengo que recurrir al VBA?

Advertisement
Advertisement

Respuestas (5)

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

Para la posteridad, aquí hay otra macro para abordar este problema.

Esta macro recorrerá una columna especificada, de arriba a abajo, y la dividirá en un nuevo archivo cada vez que encuentre un nuevo valor. Los espacios en blanco o los valores repetidos se mantienen juntos (así como el total de filas), pero los valores de sus columnas deben estar ordenados o ser únicos. Principalmente lo diseñé para trabajar con el diseño de PivotTables (una vez convertido a valores ).

Así que tal como está, no hay necesidad de modificar el código o preparar un rango con nombre. La macro comienza solicitando al usuario la columna a procesar, así como el número de fila en el que debe comenzar - es decir, saltarse las cabeceras, y parte de ahí.

Cuando se identifica una sección, en lugar de copiar esos valores a otra hoja, se copia toda la hoja de trabajo a un nuevo libro y se borran todas las filas por debajo y por encima de la sección. Esto permite mantener cualquier configuración de impresión, formato condicional, gráficos o cualquier otra cosa que pueda tener allí, así como mantener la cabecera en cada archivo dividido, lo cual es útil cuando se distribuyen estos archivos.

Los archivos se guardan en una subcarpeta \Split\ con el valor de la celda como nombre de archivo. Todavía no lo he probado extensamente en una variedad de documentos, pero funciona en mis archivos de muestra. Siéntase libre de probarlo y hágame saber si tiene problemas.

La macro se puede guardar como un complemento de Excel (xlam) para añadir un botón en la cinta de opciones/barra de herramientas de acceso rápido para facilitar el acceso.

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

Hasta donde yo sé, no hay nada que no sea una macro que vaya a dividir los datos y guardarlos automáticamente en un conjunto de archivos para usted. VBA es probablemente más fácil.

Actualización He implementado mi sugerencia. Se hace un bucle a través de todos los nombres definidos en el rango con nombre ‘RepList’. El rango con nombre es un rango dinámico con nombre de la forma =OFFSET(Names!$A$2,0,0,COUNTA(Names!$A:$A)-1,1)

el módulo sigue.

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

Este libro de trabajo contiene el código y el rango nombrado. El código forma parte de la hoja ‘Datos de Venta’.

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

Si alguien más responde con la forma correcta de hacer esto que sea rápida, por favor ignore esta respuesta.

Personalmente me encuentro usando Excel y luego pasando mucho tiempo (a veces horas) buscando una forma complicada de hacer algo o una ecuación exagerada que lo haga todo cuando nunca lo voy a volver a usar… y resulta que si simplemente me sentara y me pusiera a hacer la tarea manualmente me llevaría una fracción del tiempo.

  • *

Si sólo tienes un puñado de personas, lo que te recomiendo que hagas es simplemente resaltar todos los datos, ir a la pestaña de datos y hacer clic en el botón de ordenar.

Luego puedes elegir por qué columna ordenar, en tu caso quieres usar Repname, luego sólo tienes que copiar y pegar en los archivos individuales.

Estoy seguro de que usando VBA u otras herramientas, puedes llegar a una solución, pero el hecho es que te encontrarás con horas y horas de trabajo, cuando con el método anterior deberías hacerlo en poco tiempo.

Además, creo que se puede hacer este tipo de cosas en sharepoint + excel services, pero eso es una solución excesiva para este tipo de cosas.

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

OK, así que aquí está el primer corte de la VBA. Lo llamas así:

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

Donde A1:N1 es tu(s) fila(s) de cabecera, A2:N2 es la primera fila de tus datos, B2 es la primera celda de tu columna clave preordenada. El último argumento es el prefijo del nombre del archivo. La clave se añadirá a éste antes de guardar.

Aviso: este código es desagradable.

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
Advertisement
-2
-2
2012-12-11 08:32:17 +0000
Advertisement

Ordeno por nombre y pego la información directamente en una segunda hoja de Excel, la que quieres enviar. Excel pega sólo las líneas que se ven, no también las filas ocultas. También protejo todas las celdas excepto las que quiero que actualicen. lol.

Advertisement

Preguntas relacionadas

6
13
9
10
5
Advertisement
Advertisement