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

Posso dividere un foglio di calcolo in più file in base a una colonna in Excel 2007?

Advertisement

C'è un modo in Excel per dividere un grande file in una serie di file più piccoli, basati sul contenuto di una singola colonna?

es: Ho un file di dati di vendita per tutti i rappresentanti. Ho bisogno di inviare loro un file per fare delle correzioni e rimandarlo indietro, ma non voglio inviare a ciascuno di loro l'intero file (perché non voglio che cambino i dati degli altri). Il file assomiglia a questo:

salesdata.xls

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

di questo ho bisogno:

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

C'è qualcosa di integrato in Excel 2007 per fare questo automaticamente, o devo tirar fuori il VBA?

Advertisement
Advertisement

Réponses (5)

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

Per i posteri, ecco un'altra macro per affrontare questo problema.

Questa macro passerà attraverso una colonna specificata, dall'alto verso il basso, e dividerà in un nuovo file ogni volta che si incontra un nuovo valore. Gli spazi vuoti o i valori ripetuti sono tenuti insieme (così come il totale delle righe), ma i vostri valori di colonna devono essere ordinati o unici. L'ho progettato principalmente per lavorare con il layout di PivotTables (una volta convertito in valori ).

Così com'è, non c'è bisogno di modificare il codice o di preparare un intervallo denominato. La macro inizia chiedendo all'utente la colonna da processare, così come il numero di riga da cui partire - cioè saltare le intestazioni, e va da lì.

Quando viene identificata una sezione, piuttosto che copiare quei valori in un altro foglio, l'intero foglio di lavoro viene copiato in una nuova cartella di lavoro e tutte le righe sotto e sopra la sezione vengono eliminate. Questo permette di mantenere qualsiasi impostazione di stampa, formattazione condizionale, grafici o qualsiasi altra cosa si possa avere lì dentro, così come mantenere l'intestazione in ogni file diviso, che è utile quando si distribuiscono questi file.

I file vengono salvati in una sottocartella “Split” con il valore della cella come nome del file. Non l'ho ancora testato estensivamente su una varietà di documenti, ma funziona sui miei file di esempio. Sentitevi liberi di provarla e fatemi sapere se avete problemi.

La macro può essere salvata come un add-in di Excel (xlam) per aggiungere un pulsante sulla barra multifunzione / barra degli strumenti di accesso rapido per un facile accesso.

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

Per quanto ne so non c'è niente di meglio di una macro che ti divida i dati e li salvi automaticamente su una serie di file per te. VBA è probabilmente più facile.

Aggiornamento Ho implementato il mio suggerimento. Esegue il loop attraverso tutti i nomi definiti nell'intervallo denominato ‘RepList’. L'intervallo denominato è un intervallo dinamico della forma =OFFSET(Nomi!$A$2,0,0,0,COUNTA(Nomi!$A:$A)-1,1)

il modulo segue.

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

Questa cartella di lavoro contiene il codice e l'intervallo nominato. Il codice fa parte del foglio ‘Dati di vendita’.

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

Se qualcun altro risponde con il modo corretto di fare questo che è veloce, si prega di ignorare questa risposta.

Personalmente mi ritrovo ad usare Excel e poi a passare un sacco di tempo (a volte ore) a cercare un modo complicato per fare qualcosa o un'equazione esagerata che farà tutto quando non la userò mai più… e si scopre che se mi sedessi e mi mettessi a fare il lavoro manualmente ci vorrebbe una frazione del tempo.


Se avete solo una manciata di persone, quello che vi consiglio di fare è semplicemente evidenziare tutti i dati, andare alla scheda dati e cliccare sul pulsante ordina.

Puoi poi scegliere per quale colonna ordinare, nel tuo caso vuoi usare Repname, poi basta copiare e incollare nei singoli file.

Sono sicuro che usando VBA o altri strumenti, potresti trovare una soluzione, ma il fatto è che ti aspettano ore e ore di lavoro, mentre con il metodo di cui sopra dovresti riuscire a finire in pochissimo tempo.

Inoltre, penso che si possa fare questo genere di cose su sharepoint + servizi excel, ma è una soluzione troppo complessa per questo genere di cose.

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

OK, ecco il primo taglio del VBA. Lo chiami in questo modo:

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

dove A1:N1 è la tua riga o le tue righe di intestazione, A2:N2 è la prima riga dei tuoi dati, B2 è la prima cella nella tua colonna chiave preordinata. L'ultimo argomento è il prefisso del nome del file. La chiave sarà aggiunta a questo prima del salvataggio.

Disclaimer: questo codice è brutto.

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

Ordino per nome e incollo le informazioni direttamente in un secondo foglio Excel, quello che vuoi spedire. Excel incolla solo le righe che si vedono, non anche le righe nascoste. Proteggo anche tutte le celle tranne quelle che voglio che vengano aggiornate. lol.

Advertisement

Questions connexes

6
9
13
9
10
Advertisement