Ir para o conteúdo principal

Como exportar e salvar cada planilha como uma nova pasta de trabalho separada em Excel?

Digamos que você queira exportar e salvar uma ou várias planilhas como uma nova pasta de trabalho, como você lidará com isso? Normalmente, você pode copiar cada planilha e colar em uma nova pasta de trabalho. Mas aqui trazemos alguns truques úteis para lidar com isso:

Exportar e salvar planilhas como uma nova pasta de trabalho com o comando Mover ou Copiar

Exportar e salvar planilhas como uma nova pasta de trabalho com código VBA

Exporte e salve planilhas como uma nova pasta de trabalho com Kutools for Excel boa ideia 3


seta azul bolha direita Exportar e salvar planilhas como uma nova pasta de trabalho com o comando Mover ou Copiar

Com o Mover ou Copiar comando ajudará você a exportar ou copiar uma ou várias planilhas para uma nova pasta de trabalho rapidamente.

Etapa 1: Selecione os nomes da planilha na barra de guias. Você pode selecionar vários mantendo pressionado Ctrl chave ou mudança chave.

Etapa 2: clique com o botão direito no nome da planilha e clique no Mover ou Copiar no menu de contexto.
folhas de exportação doc 1

Etapa 3: em Mover ou Copiar caixa de diálogo, selecione o (livro novo) item da lista suspensa de Mover folhas selecionadas para livro.

folhas de exportação doc 2

Etapa 4: clique em OK, agora você mudou para o nova pasta de trabalho com planilhas exportadas ou copiadas, clique Envie o > Salvar para salvar a nova pasta de trabalho.

Nota: Na série Mover ou Copiar caixa de diálogo, há um Crie uma cópia opção. Se você não marcar, removerá as planilhas selecionadas da pasta de trabalho original; se marcar, copiará as planilhas selecionadas.


Divida rapidamente várias planilhas em pastas de trabalho separadas em Excel

No Microsoft Excel, você pode salvar ou dividir uma planilha de uma pasta de trabalho como uma nova Excel arquivo copiando e colando esta planilha em uma nova pasta de trabalho. Parece problemático se você deseja dividir cada planilha/planilha de uma pasta de trabalho grande como separada Excel, txt, csv, arquivos pdf. Mas com Kutools for Excel'S Dividir a pasta de trabalho utilitário, você pode lidar com isso rapidamente.  Clique para 30 dias de avaliação gratuita com recursos completos!
doc divisão pasta de trabalho 1
 
Kutools for Excel: com mais de 300 úteis Excel suplementos, gratuitos para testar, sem limitação de 30 dias.

seta azul bolha direita Exportar e salvar planilhas como uma nova pasta de trabalho com código VBA

O código a seguir exportará todas as planilhas visíveis em uma nova pasta de trabalho e salvará a pasta de trabalho com o nome da planilha original em uma pasta recém-criada no mesmo caminho da pasta de trabalho ativa. Siga as seguintes etapas:

Etapa 1: Mantenha pressionado o botão ALT + F11 chaves, e abre o Microsoft Visual Basic para Aplicações janela.

Etapa 2: clique inserção > Móduloe cole a seguinte macro na janela do módulo:

VBA: Exporte e salve planilhas como uma nova pasta de trabalho em uma nova pasta.

Sub SplitWorkbook()
'Updateby20200806
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim xWs As Worksheet
Dim xWb As Workbook
Dim xNWb As Workbook
Dim FolderName As String
Application.ScreenUpdating = False
Set xWb = Application.ThisWorkbook

DateString = Format(Now, "yyyy-mm-dd hh-mm-ss")
FolderName = xWb.Path & "\" & xWb.Name & " " & DateString

If Val(Application.Version) < 12 Then
    FileExtStr = ".xls": FileFormatNum = -4143
Else
    Select Case xWb.FileFormat
        Case 51:
            FileExtStr = ".xlsx": FileFormatNum = 51
        Case 52:
            If Application.ActiveWorkbook.HasVBProject Then
                FileExtStr = ".xlsm": FileFormatNum = 52
            Else
                FileExtStr = ".xlsx": FileFormatNum = 51
            End If
        Case 56:
            FileExtStr = ".xls": FileFormatNum = 56
        Case Else:
            FileExtStr = ".xlsb": FileFormatNum = 50
        End Select
End If

MkDir FolderName

For Each xWs In xWb.Worksheets
On Error GoTo NErro
    If xWs.Visible = xlSheetVisible Then
    xWs.Select
    xWs.Copy
    xFile = FolderName & "\" & xWs.Name & FileExtStr
    Set xNWb = Application.Workbooks.Item(Application.Workbooks.Count)
    xNWb.SaveAs xFile, FileFormat:=FileFormatNum
    xNWb.Close False, xFile
    End If
NErro:
    xWb.Activate
Next

    MsgBox "You can find the files in " & FolderName
    Application.ScreenUpdating = True
End Sub

Etapa 3: pressione o F5 chave para executar este código. E uma caixa de prompt aparecerá para informar a localização das novas pastas de trabalho exportadas, e todas as planilhas da pasta de trabalho original foram exportadas para algumas novas pastas de trabalho separadas que nomearam as planilhas originais em uma nova pasta específica. Veja as capturas de tela:

folhas de exportação doc 7

seta azul bolha direita Exporte e salve planilhas como uma nova pasta de trabalho com Kutools for Excel

Se você tiver várias planilhas que precisam ser salvas como uma pasta de trabalho separada, o primeiro método não pode ser uma boa escolha. E o código VBA talvez seja um pouco complicado para Excel iniciantes. Aqui você pode usar o Dividir a pasta de trabalho utilidade de Kutools for Excel para exportar e salvar de forma rápida e fácil cada planilha de uma pasta de trabalho para separar a nova pasta de trabalho.

Kutools for Excel, com mais de 300 funções úteis, tornam seus trabalhos mais fáceis. 

Depois de instalação grátis Kutools for Excel, faça o seguinte:

Etapa 1: clique Kutools MAIS > livro > Dividir a pasta de trabalho .... Veja a imagem:
folhas de exportação doc 3

Etapa 2: no Dividir a pasta de trabalho caixa de diálogo, faça o seguinte:

folhas de exportação doc 4
1: todos os nomes das planilhas foram marcados por padrão, se você não quiser dividir algumas das planilhas, você pode desmarcá-las;


2: Se quiser evitar a divisão de planilhas ocultas ou em branco, você pode verificar o Pular planilhas ocultas or Pular planilhas em branco) .;


3: e você também pode verificar Especifique salvar e para selecionar dividir as planilhas, salve como arquivo de texto, arquivo pdf ou arquivo csv, no padrão, se você não marcar esta opção, irá dividir as planilhas e salvar como pasta de trabalho.

Etapa 3: clique em Split e escolha a pasta na qual deseja colocar as novas pastas de trabalho. Veja a imagem:
folhas de exportação doc 6

Etapa 4: e clique em OK, então cada planilha marcada no Dividir a pasta de trabalho a caixa de diálogo é exportada e salva como uma pasta de trabalho individual. Cada nova pasta de trabalho é nomeada com o nome da planilha original. Veja a imagem:
folhas de exportação doc 5

Clique para saber mais informações sobre esta ferramenta Split Workbook.

seta azul bolha direita Exporte e salve cada planilha como uma nova pasta de trabalho


Divida rapidamente os dados em várias planilhas com base em colunas ou linhas fixas em Excel

Supondo que você tenha uma planilha com dados nas colunas A a G, o nome do vendedor está na coluna A e você precisa dividir automaticamente esses dados em várias planilhas com base na coluna A na mesma pasta de trabalho e cada vendedor será dividido em um novo planilha. Kutools for Excel'S Data de Divisão O utilitário pode ajudá-lo a dividir rapidamente os dados em várias planilhas com base na coluna selecionada, conforme a captura de tela abaixo mostrada em Excel.  Clique para recursos completos 30 dias de teste grátis!
doc dividir dados 2
 
Kutools for Excel: com mais de 300 úteis Excel suplementos, gratuitos para testar, sem limitação de 30 dias.

Artigos relacionados:

Melhores ferramentas de produtividade de escritório

Turbine suas planilhas: Experimente eficiência como nunca antes com Kutools for Excel

Recursos mais comuns: Localizar/destacar/identificar duplicatas   |  Excluir linhas em branco   |  Combine colunas ou células sem perder dados   |   Rodada sem Fórmula ...
Super pesquisa: VLookup de múltiplos critérios    VLookup de múltiplos valores  |   VLookup em várias planilhas   |   Pesquisa Difusa ....
Lista suspensa avançada: Crie rapidamente uma lista suspensa   |  Lista suspensa de dependentes   |  Lista suspensa de seleção múltipla ....
Gerenciador de colunas: Adicione um número específico de colunas     Mover colunas   |   Exibir colunas   |   Comparar colunas com Selecionar células iguais e diferentes ...
Recursos em destaque: Foco da Grade   |  Vista de Design   |   Grande Barra de Fórmula    Gerenciador de pastas de trabalho e planilhas   |  Biblioteca (Auto texto)   |  Data Picker   |  Combinar planilhas   |  Criptografar/Descriptografar Células    Enviar e-mails por lista   |  Super Filtro   |   Filtro Especial (filtro negrito/itálico/tachado...) ...
15 principais conjuntos de ferramentas12 Texto Ferramentas (Adicionar texto, Remover Personagens, ...)   |   50+ de cores Tipos (Gráfico de Gantt, ...)   |   Mais de 40 práticos Fórmulas (Calcule a idade com base no aniversário, ...)   |   19 Inclusão Ferramentas (Insira o código QR, Inserir imagem do caminho, ...)   |   12 Conversão Ferramentas (Números para Words, Conversão de moedas, ...)   |   7 Unir e dividir Ferramentas (Combinar linhas avançadas, Dividir células, ...)   |   Muito mais...

Kutools for Excel possui mais de 300 recursos, garantindo que o que você precisa está a apenas um clique de distância...

Suporta Escritório/Excel 2007-2021 e mais recentes, incluindo 365 | Disponível em 44 idiomas | Desfrute de um teste gratuito de 30 dias com todos os recursos.

guia kte 201905


Office Tab Traz a interface com guias para o Office e torna seu trabalho muito mais fácil

  • Ative a edição e leitura com guias em Word, Excel, Power Point, Publisher, Access, Visio e Project.
  • Abra e crie vários documentos em novas guias da mesma janela, em vez de em novas janelas.
  • Aumenta sua produtividade em 50% e reduz centenas de cliques do mouse para você todos os dias!

Comments (63)
Rated 5 out of 5 · 1 ratings
This comment was minimized by the moderator on the site
Thanks, this was awesome. There are dozens of pages on the internet talking about how to do this. You guys are the only ones that got the VBA code right. Many thanks. I had a big monster workbook with about 100 tabs, all relatively small, and the VBA macro knocked it out in about five minutes. Thank God for smart guys like you. :)
Rated 5 out of 5
This comment was minimized by the moderator on the site
This has been extremely helpful, my job was doing some data management manually and this helped me automate it. I do have a question though, as the code is a bit over my head to figure out on my own.

What would I need to change to make it so that it always saves as a CSV file instead of an excel file? I know it'll be part of the IF VAL THEN CASES but I don't follow the formatting of that area.

Thank you,
Matt
This comment was minimized by the moderator on the site
Hi, Matt, I am glad that this article can help you. If you want to save sheets as new CSV files, this article https://www.extendoffice.com/documents/excel/5537-excel-batch-convert-to-csv.html lists the methods on exporting sheets as separated CSV files, hope it can do you a favor.
This comment was minimized by the moderator on the site
I have been using this VBA Code for some time and it worked like a charm until I changed computers. I have the same version of excel but now I am getting a Run Time Error "76" Path Not found. Any ideas what could be causing this? It looks like it is hanging up at MkDir. Any help you can provide is appreciated.
This comment was minimized by the moderator on the site
Hi, can I ask which office version you use?
This comment was minimized by the moderator on the site
I'm having this issue as well. I ran it once a month ago just fine and this came up just now.
This comment was minimized by the moderator on the site
You are amazing! Thank you so very much!
This comment was minimized by the moderator on the site
Thank you so much ! great and useful.
This comment was minimized by the moderator on the site
For Each xWs In xWb.Worksheets
How to do export only selected / grouped sheets to separate excel sheets by using this code.?
This comment was minimized by the moderator on the site
Hi there,

Keep getting a pop up that says 'compile error, invalid outside procedure' when i try and run the code. Any thoughts? Thanks for all your help.
This comment was minimized by the moderator on the site
Hi, Issybeee, I have update the VBA code in the tutorial, you can try the new one again.
This comment was minimized by the moderator on the site
For those of you who save macros in your "Personal.XLSB" or XLSTART (I see more questions below related to this), change the line

Set xWb = Application.ThisWorkbook to

Set xWB = ActiveWorkbook

That will make the macro run from the Active Workbook instead and save in a subfolder to that.
This comment was minimized by the moderator on the site
With the first method, if I hit F5, it opens a pop up window with the function "Go to". My excel is in spanish, im not sure if that is a factor. Any idea on how to fix it?
This comment was minimized by the moderator on the site
You can directly click the Run button of the Microsoft Visual Basic for Applications window.
This comment was minimized by the moderator on the site
Un aporte realmente útil. He probado el módulo con código VBA y funciona a la perfección. Muchas gracias, me has salvado una tarea que me hubiera llevado mucho tiempo con el mover y copiar.
This comment was minimized by the moderator on the site
This is a fantastic piece of work, thanks a lot.
Do we have any option to select only specific columns in a worksheet to be exported?
This comment was minimized by the moderator on the site
Hi, SS, if you want to export a specific selection as a individual file, this article can help you https://www.extendoffice.com/documents/excel/626-excel-save-selection.html
This comment was minimized by the moderator on the site
For anybody who finds the VBA code is not running as expected, try to change Line 9 to "Set xWb = Application.ActiveWorkbook"

Otherwise, fantastic! Does exactly as described, and runs fairly quickly
This comment was minimized by the moderator on the site
very nice.... Thanks
This comment was minimized by the moderator on the site
How to convert this macro so that I can save it in my personal workbook and can use to where ever I need it.
This comment was minimized by the moderator on the site
Click Developer tab > Record Macro > select Personal Macro Workbook, and give the vba a name.
Then in Microsoft Visual Basic for Applications window, click VBAProject(PERSONA_XLSB) > Modules > double click Module1, paste the code between Sub() and End Sub, save the code.
When you want to use the code, click Developer > Macro, choose the code you name.
This comment was minimized by the moderator on the site
xWs.Copy this methode give me an erreor 1004
This comment was minimized by the moderator on the site
February 2019 - after some update Excel silently exits macro right after Application.ActiveWorkbook.SaveAs
It means, that commands Application.ActiveWorkbook.Close does not run and file stays opened... Could it be fixed? This happened all the machines in our office on several workbooks that were using such kind of Macro.
This comment was minimized by the moderator on the site
Do you have the formula to make sure that each excel sheet when saved as a new work book is in total format Comma Delimited .CSV
This comment was minimized by the moderator on the site
Sorry, I have no idea,neither.
This comment was minimized by the moderator on the site
Love this and another info you have on splitting data into each worksheet. However I keep getting an error when trying to upload my single reports into my system

I needed them as a csv file so just changed the last part of the module to .csv I am wondering if I missed something else that should've been changed.

Thanks a million
This comment was minimized by the moderator on the site
what is the use of Worksheet.Save??
This comment was minimized by the moderator on the site
to save the changes made
This comment was minimized by the moderator on the site
What? I do not understand.
This comment was minimized by the moderator on the site
Hi Sunny,

Thank you for sharing this code!

I keep getting this error "Compile Error: Wrong number of arguments or invalid property assignment" at the "format" portion of the following string:

DateString = format(Now, "yyyy-mm-dd hh-mm-ss")
This comment was minimized by the moderator on the site
Hi, I use this VBA code all the time to separate commission statements into individual spreadsheets. Is it possible to add a line to the code so it will automatically email the report to each person using outlook?
This comment was minimized by the moderator on the site
Soryy I did not know a code can do that, but you can split the workbook first, then apply Kutools for Excel's Create Mailing List and Send Emails utilities to create a mailing list, and then send the reports as attachments to each person. For more detail, please go to visit this article https://www.extendoffice.com/product/kutools-for-excel/excel-create-mailing-list-and-send-email.html
This comment was minimized by the moderator on the site
i cant find enterprise toolbar kindly help me
This comment was minimized by the moderator on the site
this code cahnge dates in my sheets
This comment was minimized by the moderator on the site
What dates have been changed? The modified dates? The Enterprise tab will be appeared after installing Kutools for Excel.
This comment was minimized by the moderator on the site
xWs.Copy line comes up with an error in my case with 2016 "Method 'Copy of object'_Worksheet' failed.
Please suggest me a correction if possible.
This comment was minimized by the moderator on the site
Sorry, I have no idea about your problem.
This comment was minimized by the moderator on the site
Hi,


its totally work with the excel 2010.


however, after i upgraded to Excel 2016, the code doesn't work.


would you please advise which part should i be revised?
This comment was minimized by the moderator on the site
Excuse me, which method you cannot use in Excel 2016? In my condition, all of the methods above do work in Excel 2016 perfectly
This comment was minimized by the moderator on the site
Hi the second method worked great. Thank you. I have one question. This method saves each worksheet as a new workbook based on the name of the sheet. Is there anyway to add to the name, for example sheets have a variable name which is currently being saved. Can I add January 2017 or Feb 2017 to the files saved?
This comment was minimized by the moderator on the site
Thanks for your leaving message, you can apply Kutools for Excel's Rename Multiple Worksheets to rename every sheets of the workbook firstly, then use one of above methods to export or save the sheets separately as workbook. If you want to know more detail on Rename Multiple Worksheet utility, please visit this:https://www.extendoffice.com/product/kutools-for-excel/batch-rename-excel-worksheets.html
This comment was minimized by the moderator on the site
Is there a way to change this macro so I can save it in a file in the XLSTART folder but it will run for the active workbook? Everytime I save it in the XLSTART workbook it fails at the DateString = Format(Now, "yyyy-mm-dd hh-mm-ss")line. Thanks! Sarfraz
This comment was minimized by the moderator on the site
This is exactly what I needed! Awesome!
This comment was minimized by the moderator on the site
Hi. I received an error code that says "Compile error: Invalid outside procedure"...help!
This comment was minimized by the moderator on the site
Your code worked for me... Thanks much!!!
This comment was minimized by the moderator on the site
Can we also export ALL (300+) sheets to html, this will help me a lot, the export to unified text is already helping but I need them in html, or no table borders for the cell differences
This comment was minimized by the moderator on the site
Out of the above three methods, I found the first method to be quite good having regard to the fact that I am a beginner & my work is not at all of the same magnitude like professionals. My sincere thanks for explaining the steps in simple and lucid manner.
This comment was minimized by the moderator on the site
Run time error Method 'Copy of Object' worksheet' failed
This comment was minimized by the moderator on the site
xWs.Copy -it is an error in my part what does it mean?
This comment was minimized by the moderator on the site
Great article - VBA worked first time - perfect
This comment was minimized by the moderator on the site
Unfortunately the VBA code didn't work for me. I had to debug and the issue is with the line: Application.ActiveWorkbook.SaveAs xFile, FileFormat:=FileFormatNum Any ideas why it didn't work for me?
This comment was minimized by the moderator on the site
Muy buena la aplicacion. Es una pena no existir tambien en Español. Gracias
This comment was minimized by the moderator on the site
Very Useful thanks! Loved the VBA Code
This comment was minimized by the moderator on the site
thank. terimakasih. ini code yang saya butuhkan
This comment was minimized by the moderator on the site
The VBA codes works like magic, but is there a way for this to be done using VBScript? I'm going nuts trying to meet the requirement from my supervisor.
This comment was minimized by the moderator on the site
this code is perfect for what i need, but could you show code for the exact same process for one sheet rather than the entire workbook?
This comment was minimized by the moderator on the site
The code is failing at sh.Copy and I cannot figure out why. Any Ideas?
This comment was minimized by the moderator on the site
Thank you. This is esactly what I needed.
This comment was minimized by the moderator on the site
Hi All, Can someone help me on below. I need VBA code that can copy only all visible sheets to new workbook and it should not copy macro code to new workbook, save new workbook on desktop with two different cell values in sheet and sheet name as a file name and close the master workbook without saving.
This comment was minimized by the moderator on the site
Is there a way to change this macro so I can save it in a file in the XLSTART folder but it will run for the active workbook? Everytime I save it in the XLSTART workbook it fails at the DateString = Format(Now, "yyyy-mm-dd hh-mm-ss")line. Thanks! Keith
This comment was minimized by the moderator on the site
Thanks a lot. Good Job!.
This comment was minimized by the moderator on the site
Hello I like the code Is it possible to just save the new workbook without the date information That is so when I resave the sheets in the previous workbook I will have the option to overwrite the changes rather than create another dated folder? Also but not so important how could I use another name and destination for the destination folder Regards Sean
This comment was minimized by the moderator on the site
thanks alot, works very well and easy.
There are no comments posted here yet
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations