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

Posso dividir uma folha de cálculo em vários ficheiros com base numa coluna do Excel 2007?

Advertisement

Existe alguma forma em Excel de dividir um ficheiro grande numa série de pequenos ficheiros, com base no conteúdo de uma única coluna?

eg: Tenho um ficheiro de dados de vendas para todos os representantes de vendas. Preciso de lhes enviar um ficheiro para fazer correcções e enviar de volta, mas não quero enviar a cada um deles o ficheiro completo (porque não quero que alterem os dados uns dos outros). O ficheiro é algo parecido com isto:

salesdata.xls

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

fora disto eu preciso:

salesdata_Adam.xls

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

e salesdata_Bob.xls

Bob Cust3 blah@cust3.com

Existe algo incorporado no Excel 2007 para fazer isto automaticamente, ou devo quebrar o VBA?

Advertisement
Advertisement

Respostas (5)

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

Para a posteridade, aqui está mais uma macro para enfrentar este problema.

Esta macro passará por uma coluna especificada, de cima para baixo, e será dividida num novo ficheiro sempre que for encontrado um novo valor. Os espaços em branco ou valores repetidos são mantidos juntos (bem como o total de linhas), mas os valores da sua coluna devem ser classificados ou únicos*. Concebi-o principalmente para trabalhar com a disposição das Tabelas PivotTables (uma vez convertido em valores ).

Assim como está, não há necessidade de modificar o código ou preparar um intervalo nomeado. A macro começa por pedir ao utilizador para a coluna processar, bem como o número da linha em que deve começar - isto é, saltar os cabeçalhos, e vai a partir daí.

Quando uma secção é identificada, em vez de copiar esses valores para outra folha, toda a folha de trabalho é copiada para uma nova pasta de trabalho e todas as linhas abaixo e acima da secção são eliminadas. Isto permite manter qualquer configuração de impressão, formatação condicional, gráficos ou qualquer outra coisa que possa ter aí, bem como manter o cabeçalho em cada ficheiro dividido, o que é útil quando se distribuem estes ficheiros.

Os ficheiros são guardados numa subpasta \i1 com o valor da célula como o nome do ficheiro. Ainda não o testei extensivamente numa variedade de documentos, mas funciona nos meus ficheiros de amostra. Sinta-se à vontade para o experimentar e avise-me se tiver problemas.

A macro pode ser guardada como um excelente add-in (xlam) para adicionar um botão no botão da barra de ferramentas de fita/acesso rápido para fácil acesso.

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

Tanto quanto sei, não há nada menos do que uma macro que lhe vai dividir os dados e guardá-los automaticamente num conjunto de ficheiros para si. A VBA é provavelmente mais fácil.

Actualizei a minha sugestão. Ela percorre todos os nomes definidos no intervalo designado ‘RepList’. O intervalo nomeado é um intervalo dinâmico do formulário =OFFSET(Names!$A$2,0,0,0,COUNTA(Names!$A:$A)-1,1)

módulo seguinte.

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

Esta pasta de trabalho contém o código e o intervalo nomeado. O código faz parte da folha ‘Dados de Vendas’.

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

Se outra pessoa responder com a forma correcta e rápida de o fazer, por favor ignore esta resposta.

Eu pessoalmente encontro-me a usar Excel e depois passo muito tempo (algumas vezes horas) à procura de uma maneira complicada de fazer algo ou de uma equação exagerada que fará tudo quando eu nunca mais a usarei… e acontece que se eu apenas me sentasse e continuasse com a tarefa manualmente, levaria uma fracção do tempo.


Se tiver apenas um punhado de pessoas, o que recomendo é simplesmente destacar todos os dados, ir ao separador de dados e clicar no botão de ordenação.

Pode então escolher por que coluna ordenar, no seu caso quer usar Repname, depois basta copiar e colar em ficheiros individuais.

Tenho a certeza de que utilizando VBA ou outras ferramentas, poderá encontrar uma solução, mas o facto é que estará a olhar para horas e horas de trabalho quando simplesmente começar a utilizar o método acima descrito deverá fazê-lo em pouco tempo.

Além disso, penso que pode fazer este tipo de coisa em serviços sharepoint + excel, mas isso é uma forma de ultrapassar a solução de topo para este tipo de coisas.

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

OK, então aqui está o primeiro corte da VBA. Chama-lhe assim:

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

Onde A1:N1 é a(s) sua(s) linha(s) de cabeçalho, A2:N2 é a primeira linha dos seus dados, B2 é a primeira célula da sua coluna chave pré-seleccionada. O último argumento é o prefixo do nome do ficheiro. A chave será anexada a este antes de guardar.

Exoneração de responsabilidade: este código é desagradável.

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 pelo nome e colo a informação directamente numa segunda folha Excel, aquela que se pretende enviar. O Excel cola apenas as linhas que vê, não também as linhas ocultas. Também protejo todas as células excepto as células que quero que sejam actualizadas. lol.

Advertisement

Questões relacionadas

6
13
9
10
3
Advertisement
Advertisement