Notifications
Clear all

Separar dados em planilhas

6 Posts
2 Usuários
0 Reactions
728 Visualizações
(@fernandofernandes)
Posts: 43750
Illustrious Member
Topic starter
 

Boa tarde pessoal!

Estou utilizando um código feito pelo AlexandreVBA (http://www.planilhando.com.br/forum/viewtopic.php?f=20&t=14764 para separar os dados de uma planilha em várias "ABAS".

Rem Attribute VBA_ModuleType=VBAModule
Option VBASupport 1
Option Explicit
Sub ParseItems()
'Author:    Jerry Beaucaire
'Date:      11/11/2009
'Summary:   Based on selected column, data is filtered to individual sheets
'           Creates sheets and sorts sheets alphabetically in workbook
'           6/10/2010 - added check to abort if only one value in vCol
'           7/22/2010 - added ability to parse numeric values consistently
'           11/16/2011 - changed way Unique values are collected, no Adv Filter
'           12/23/2013 - option to append incoming data
Dim LR As Long, Itm As Long, MyCount As Long, vCol As Long, iCol As Long, NR As Long
Dim ws As Worksheet, MyArr As Variant, vTitles As String, TitleRow As Long, Append As Boolean

Application.ScreenUpdating = False

'Column to evaluate from, column A = 1, B = 2, etc.
   vCol = 7
 
'Sheet with data in it
   Set ws = Sheets("Relatório")

'option to append new data below old data
If MsgBox(" If sheet exists already, add new data to the bottom?" & vbLf & _
           "(if no, new data will replace old data)", _
           vbYesNo, "Append new Data?") = vbYes Then Append = True
'Range where titles are across top of data, as string, data MUST
'have titles in this row, edit to suit your titles locale
    vTitles = "A11:G11"
    TitleRow = Range(vTitles).Cells(1).Row

'Spot bottom row of data
   LR = ws.Cells(ws.Rows.Count, vCol).End(xlUp).Row

'Get a temporary list of unique values from vCol
    iCol = ws.Columns.Count
    ws.Cells(11, iCol) = "key"
    
    For Itm = TitleRow + 1 To LR
        On Error Resume Next
        If ws.Cells(Itm, vCol) <> "" And Application.WorksheetFunction _
            .Match(ws.Cells(Itm, vCol), ws.Columns(iCol), 0) = 0 Then
               ws.Cells(ws.Rows.Count, iCol).End(xlUp).Offset(1) = ws.Cells(Itm, vCol)
        End If
    Next Itm
'Sort the temporary list
    ws.Columns(iCol).Sort Key1:=ws.Cells(2, iCol), Order1:=xlAscending, _
        Header:=xlYes, OrderCustom:=1, MatchCase:=False, _
        Orientation:=xlTopToBottom, DataOption1:=xlSortNormal

'Put list into an array for looping
    MyArr = Application.WorksheetFunction.Transpose _
        (ws.Columns(iCol).SpecialCells(xlCellTypeConstants))

'clear temporary list
    ws.Columns(iCol).Clear

'Turn on the autofilter
    ws.Range(vTitles).AutoFilter

'Loop through list one value at a time
'The array includes the title cell, so we start at the second value in the array
    For Itm = 2 To UBound(MyArr)
        ws.Range(vTitles).AutoFilter Field:=vCol, Criteria1:=CStr(MyArr(Itm))
    
        If Not Evaluate("=ISREF('" & CStr(MyArr(Itm)) & "'!A1)") Then   'create sheet if needed
            Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = CStr(MyArr(Itm))
            NR = 1
        Else                                                            'if it exists already
            Sheets(CStr(MyArr(Itm))).Move After:=Sheets(Sheets.Count)   'ordering the sheets
            If Append Then                                              'find next empty row
                NR = Sheets(CStr(MyArr(Itm))).Cells(Rows.Count, vCol).End(xlUp).Row + 1
            Else
                Sheets(CStr(MyArr(Itm))).Cells.Clear                    'clear data if not appending
                NR = 1
            End If
        End If
    
        If NR = 1 Then                                                  'copy titles and data
            ws.Range("A" & TitleRow & ":A" & LR).EntireRow.Copy Sheets(CStr(MyArr(Itm))).Range("A" & NR)
        Else                                                            'copy data only
            ws.Range("A" & TitleRow + 1 & ":A" & LR).EntireRow.Copy Sheets(CStr(MyArr(Itm))).Range("A" & NR)
        End If
        
        ws.Range(vTitles).AutoFilter Field:=vCol                        'reset the autofilter
        If Append And NR > 1 Then NR = NR - 1
        MyCount = MyCount + Sheets(CStr(MyArr(Itm))).Range("A" & Rows.Count).End(xlUp).Row - NR
        Sheets(CStr(MyArr(Itm))).Columns.AutoFit
    Next Itm
    
'Cleanup
    ws.Activate
    ws.AutoFilterMode = False
    MsgBox "Rows with data: " & (LR - TitleRow) & vbLf & "Rows copied to other sheets: " _
                & MyCount & vbLf & "Hope they match!!"

    Application.ScreenUpdating = True
End Sub

Este código está funcionando perfeitamente!

Porém, preciso que este código separe em "PLANILHAS" e não em abas.

Será possível adaptar neste código?

Desde já agradeço!

 
Postado : 05/05/2016 11:31 am
(@mprudencio)
Posts: 0
New Member
 

Se disponibilizar a planilha fica mais facil

 
Postado : 05/05/2016 11:58 am
(@fernandofernandes)
Posts: 43750
Illustrious Member
Topic starter
 

Boa tarde!

Segue planilha de exemplo.

O código cria várias abas.
Gostaria que ele criasse várias Planilhas(diferentes arquivos).

Desde já agradeço.

Att,

 
Postado : 05/05/2016 12:32 pm
(@mprudencio)
Posts: 0
New Member
 

Esse é o seu arquivo?

Qual o criterio para filtrar os dados?

 
Postado : 05/05/2016 12:47 pm
(@fernandofernandes)
Posts: 43750
Illustrious Member
Topic starter
 

Este é um arquivo de exemplo.
O meu arquivo tem mais de 20mb então não é muito viável inserir aqui.

Se fizer o teste neste código deste exemplo, verá que ele cria as abas mediante as informações da coluna "G".
Onde for 01 cria uma aba, onde for 02 cria outra aba, onde for 03 cria outra aba e assim sucessivamente.

Preciso que se faça a mesma coisa só que em arquivo.
Onde for 01 cria um arquivo, onde for 02 cria outro arquivo, onde for 03 cria outro arquivo e assim sucessivamente.

Att,

 
Postado : 05/05/2016 12:56 pm
(@mprudencio)
Posts: 0
New Member
 

Vai salvar o arquivo criado com qual nome?

Não usei sua planilha como base..

Esse codigo é um exemplo que salva o resultado em uma arquivo xlsx

Sub Salvar()

Dim Cli As String
Dim Wtr As Worksheet
Dim WCli As Worksheet
Dim WCli2 As Worksheet
Dim W As Workbook
Dim Arq As String
Dim Resp As String

Application.ScreenUpdating = False
Application.DisplayAlerts = False

Set Wtr = Sheets("Transformação")
Set WCli = Sheets("Resumo Cliente")
Set WCli2 = Sheets("Clientes")
Set W = Workbooks("Filtra e Salva em XLSX")

    Cli = Wtr.Range("C4").Value
    Arq = Wtr.Range("C4").Value & " - " & Format(Date, "MMMM") & " - " & Format(Date, "YYYY")
    
    WCli2.Select
    WCli2.Range("A2").Select
    





Do While ActiveCell <> ""

If ActiveCell = Cli Then

        ActiveCell.Offset(0, 1).Select
            Selection.Copy
                WCli.Select
                    WCli.Range("E2").Select
                     Selection.PasteSpecial _
                      Paste:=xlPasteValues
           Application.CutCopyMode = False

           WCli2.Select
        
        
If ActiveCell.Offset(0, -1).Value = Cli Then
        
        GoTo Consolidar
        
End If
        
        ActiveCell.Offset(1, -1).Select
            
Else
            

        ActiveCell.Offset(1, 0).Select

End If

Loop


Consolidar:

    WCli2.Range("A2").Select

    WCli.Select
    WCli.Range("A7").Select
    WCli.Range(Selection, Selection.End(xlToRight)).Select
    WCli.Range(Selection, Selection.End(xlDown)).Select
                          Selection.ClearContents
    WCli.Range("E3").ClearContents
    WCli.Range("A7").Select
    Wtr.Select
    Wtr.Range("B7").Select

'Pesquisa todos dos dados da planilha tranformação para criação
'da planilha resumo cliente

Do While ActiveCell <> ""

If ActiveCell = Cli Then

ActiveCell.Offset(0, -1).Select

    Range(Selection, Selection.End(xlToRight)).Select
    Selection.Copy
    
    WCli.Select
    WCli.Range("A1048576").End(xlUp).Select
    ActiveCell.Offset(1, 0).Select
            Selection.PasteSpecial _
             Paste:=xlPasteValues
    ActiveCell.Offset(1, 0).Select
    Application.CutCopyMode = False

    Wtr.Select
    ActiveCell.Offset(1, 1).Select

    Else

    ActiveCell.Offset(1, 0).Select

    End If

    Loop
    

    WCli.Select
    WCli.Range("A7").Select
    WCli.Range("E3") = Application.WorksheetFunction.Sum(Columns("F:F"))
    
    Resp = MsgBox("Deseja Imprimir", vbYesNo, "Atenção")
    
    If Resp = vbYes Then
    
    WCli.PrintOut
    GoTo Sair
    
    Else
    
    Sheets("Resumo Cliente").Copy

     
'Salva o arquivo na pasta clientes
       ChDir "C:Clientes"
       
            ActiveWorkbook.SaveAs _
         Filename:="C:Clientes" _
                 & Arq & ".xlsx"
                ActiveWorkbook.Close
                

End If
 MsgBox "Dados do Cliente Salvo com Sucesso", vbOKOnly, "Resumo Clientes"
Sair:
    Wtr.Select
    Wtr.Range("A7").Select
    Application.ScreenUpdating = True
    
    W.Save
    
End Sub
 
Postado : 05/05/2016 1:08 pm