Dica: outros idiomas são traduzidos pelo Google. Você pode visitar o English versão deste link.
Entrar
x
or
x
x
Registre-se
x

or

Como converter em lotes múltiplos arquivos CSV para arquivos XLS (X) no Excel?

Para converter um arquivo CSV para o arquivo XlS ou XLSX é muito fácil para você, aplicando o recurso Salvar como. No entanto, converter vários arquivos CSV em arquivos XLS ou XLSX de uma pasta é demorado ao salvar manualmente um a um. Aqui eu introduzo um código de macro para converter rapidamente todos os arquivos CSV em arquivos XLS (x) de uma pasta.

Batch converter arquivos CSV para arquivos XlS (X) com código de macro

Guia do Office Habilitar Edição e Navegação por Guias no Office e Facilitar seu Trabalho ...
Kutools for Excel - A melhor ferramenta de produtividade do Office resolverá a maioria dos problemas do Excel
  • Reutilizar qualquer coisa: Adicione as fórmulas, gráficos e outras coisas mais usadas ou complexas aos seus favoritos e reutilize-os rapidamente no futuro.
  • Mais do que recursos de texto 20: Extrair Número da Cadeia de Texto; Extrair ou remover parte dos textos; Converta números e moedas em palavras inglesas ...
  • Mesclar Ferramentas: Várias pastas de trabalho e folhas em um; Mesclar várias células / linhas / colunas sem perder dados; Mesclar linhas duplicadas e soma ...
  • Ferramentas de divisão: Dados divididos em várias folhas com base no valor; Uma pasta de trabalho para vários arquivos Excel, PDF ou CSV; Uma coluna para várias colunas ...
  • Colar pulando Linhas ocultas / filtradas; Contagem e Soma pela cor de fundo; Criar lista de discussão e Envie e-mails pelo valor da célula...
  • Super Filtro: Crie esquemas de filtro avançados e aplique a qualquer folha; tipo por semana, dia, frequência e mais; filtros por negrito, fórmulas, comentário ...
  • Mais de recursos poderosos do 300; Funciona com o Office 2007-2019 e 365; Suporta todos os idiomas; Fácil implantação na empresa; Recursos completos Avaliação gratuita de um dia de 60.

Batch converter arquivos CSV para arquivos XlS (X) com código de macro


Para converter vários arquivos CSV de uma pasta para arquivos XLS (X), você pode fazer as seguintes etapas:

Kutools for Excel, com mais de 120 funções úteis, facilita seus trabalhos.

1. Ative uma nova pasta de trabalho, pressione Alt + F11 chaves para abrir Microsoft Visual Basic para Aplicações janela e clique em inserção > Módulo. Ver captura de tela:
doc batch convert cvs xls 1

notas: Certifique-se de que todos os arquivos CSV que deseja converter estão fechados.

2. Em seguida, cole abaixo o código de macro para o Módulo script e pressione F5 chave para executar o código.

VBA: Converta CSV para XLS

Sub CSVtoXLS()
'UpdatebyExtendoffice20170814
    Dim xFd As FileDialog
    Dim xSPath As String
    Dim xCSVFile As String
    Dim xWsheet As String
    Application.DisplayAlerts = False
    Application.StatusBar = True
    xWsheet = ActiveWorkbook.Name
    Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
    xFd.Title = "Select a folder:"
    If xFd.Show = -1 Then
        xSPath = xFd.SelectedItems(1)
    Else
        Exit Sub
    End If
    If Right(xSPath, 1) <> "\" Then xSPath = xSPath + "\"
    xCSVFile = Dir(xSPath & "*.csv")
    Do While xCSVFile <> ""
        Application.StatusBar = "Converting: " & xCSVFile
        Workbooks.Open Filename:=xSPath & xCSVFile
        ActiveWorkbook.SaveAs Replace(xSPath & xCSVFile, ".csv", ".xls", vbTextCompare), xlNormal
        ActiveWorkbook.Close
        Windows(xWsheet).Activate
        xCSVFile = Dir
    Loop
    Application.StatusBar = False
    Application.DisplayAlerts = True
End Sub

3. Na caixa de diálogo pop-up, selecione a pasta especificada que contém os arquivos CSV que deseja converter. Ver captura de tela:
doc batch convert cvs xls 2

4. Clique OK, todos os arquivos CSV na pasta selecionada foram convertidos em arquivos XLS nele.
doc batch convert cvs xls 3

Ponta: Se você deseja converter arquivos CSV em arquivos XLSX, use o código VBA abaixo.

VBA: converter arquivos CSV para XLSX

Sub CSVtoXLS()
'UpdatebyExtendoffice20170814
    Dim xFd As FileDialog
    Dim xSPath As String
    Dim xCSVFile As String
    Dim xWsheet As String
    Application.DisplayAlerts = False
    Application.StatusBar = True
    xWsheet = ActiveWorkbook.Name
    Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
    xFd.Title = "Select a folder:"
    If xFd.Show = -1 Then
        xSPath = xFd.SelectedItems(1)
    Else
        Exit Sub
    End If
    If Right(xSPath, 1) <> "\" Then xSPath = xSPath + "\"
    xCSVFile = Dir(xSPath & "*.csv")
    Do While xCSVFile <> ""
        Application.StatusBar = "Converting: " & xCSVFile
        Workbooks.Open Filename:=xSPath & xCSVFile
        ActiveWorkbook.SaveAs Replace(xSPath & xCSVFile, ".csv", ".xls", vbTextCompare), xlWorkbookDefault
        ActiveWorkbook.Close
        Windows(xWsheet).Activate
        xCSVFile = Dir
    Loop
    Application.StatusBar = False
    Application.DisplayAlerts = True
End Sub


BoaExportar intervalo para arquivo

Kutools for Excel 's Função Exportação para arquivo pode exportar ou salvar um intervalo para separar o arquivo como
livro de trabalho, pdf, texto, csv ou texto.
Clique Empreendimento > Import / Export > Exportar intervalo para arquivo.
doc exportar o alcance da célula para o arquivo

Artigos relativos:


Kutools for Excel - A Melhor Ferramenta de Produtividade no Escritório Aumenta Sua Produtividade em 80%

  • armadilha para peixes: Inserir rapidamente fórmulas complexas, gráficos e qualquer coisa que você tenha usado antes; Criptografar células com senha; Criar lista de endereços e enviar e-mails ...
  • Bar Super Fórmula (facilmente editar várias linhas de texto e fórmula); Layout de leitura (leia e edite facilmente grandes números de células); Colar para intervalo filtrado...
  • Mesclar células / linhas / colunas sem perder dados; Conteúdo de células divididas; Combinar linhas / colunas duplicadas... Prevenir Células Duplicadas; Comparar intervalos...
  • Selecione Duplicado ou Exclusivo Linhas; Selecione linhas em branco (todas as células estão vazias); Super Find e Fuzzy Find em muitos livros de trabalho; Seleção aleatória ...
  • Cópia exata Múltiplas Células sem alterar a referência da fórmula; Criar automaticamente referências para várias folhas; Inserir marcadores, Caixas de seleção e mais ...
  • Extrair texto, Adicionar texto, remover por posição, Remover espaço; Criar e imprimir subtotais de paginação; Converter entre conteúdo de células e comentários...
  • Super Filtro (salve e aplique esquemas de filtro a outras planilhas); Classificação Avançada por mês / semana / dia, frequência e mais; Filtro especial por negrito, itálico ...
  • Combinar pastas de trabalho e planilhas; Mesclar tabelas com base em colunas-chave; Dividir dados em várias planilhas; Lote Converter xls, xlsx e PDF...
  • Mais de recursos poderosos do 300. Suporta Office / Excel 2007-2019 e 365. Suporta todos os idiomas. Fácil implantação em sua empresa ou organização. Recursos completos Avaliação gratuita de um dia de 60.
kte tab 201905

A guia Office traz a interface com guias para o Office e torna seu trabalho muito mais fácil

  • Ativar edição e leitura com guias no Word, Excel, PowerPoint, 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!
fundo officetab
Say something here...
symbols left.
You are guest ( Sign Up? )
or post as a guest, but your post won't be published automatically.
Loading comment... The comment will be refreshed after 00:00.
  • To post as a guest, your comment is unpublished.
    viper · 1 months ago
    it changes my date column format from dd-mm-yyyy to dd/mm/yyyy, please can anyone help with how to prevent this script from changing column formats.
    Thanks a lot.
  • To post as a guest, your comment is unpublished.
    lisa6538 · 3 months ago
    Thanks for providing the code. I modified the code to do the XLSX to CSV batch conversion. The code is provided below.


    Sub XLSXtoCSV()
    'UpdatebyExtendoffice20170814
    Dim xFd As FileDialog
    Dim xSPath As String
    Dim xCSVFile As String
    Dim xWsheet As String
    Application.DisplayAlerts = False
    Application.StatusBar = True
    xWsheet = ActiveWorkbook.Name
    Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
    xFd.Title = "Select a folder:"
    If xFd.Show = -1 Then
    xSPath = xFd.SelectedItems(1)
    Else
    Exit Sub
    End If
    If Right(xSPath, 1) <> "\" Then xSPath = xSPath + "\"
    xXLSXFile = Dir(xSPath & "*.xlsx")
    Do While xXLSXFile <> ""
    Application.StatusBar = "Converting: " & xXLSXFile
    Workbooks.Open Filename:=xSPath & xXLSXFile
    ActiveWorkbook.SaveAs Replace(xSPath & xXLSXFile, ".xlsx", ".csv", vbTextCompare), xlCSV
    ActiveWorkbook.Close
    Windows(xWsheet).Activate
    xXLSXFile = Dir
    Loop
    Application.StatusBar = False
    Application.DisplayAlerts = True
    End Sub
    • To post as a guest, your comment is unpublished.
      Diego Jaime · 22 days ago
      Thank you for the modification, that´s what I was looking for!
  • To post as a guest, your comment is unpublished.
    Sam · 3 months ago
    One small issue with this code is that some accuracy (number of decimals) can be lost when opening a csv and saving it as xlsx.
    The way to prevent this is to select all cells right after opening, set the number of decimal places to the desired amount (15 for me personally), and *then* saving as xlsx

    Otherwise, the xlsx has less detail (less accuracy in terms of decimals) than the original csv, which can lead to problems in some applications
  • To post as a guest, your comment is unpublished.
    Rose · 3 months ago
    this macro does not show my csv file
  • To post as a guest, your comment is unpublished.
    stb · 4 months ago
    Cool bit of code. Very useful. If I'm not mistaken the code for .xlsx looks the same as the .xls code.

    This line:
    ActiveWorkbook.SaveAs Replace(xSPath & xCSVFile, ".csv", ".xls", vbTextCompare), xlWorkbookDefault

    I assume it should be: ".csv" , ".xlsx", vbTextCompare etc.
    • To post as a guest, your comment is unpublished.
      iBrezel · 4 months ago
      I've changed the code so, described above; now the script works as expected: it generates xlsx files
      • To post as a guest, your comment is unpublished.
        thy · 2 months ago
        no you haven't. it still says xls in both versions.
  • To post as a guest, your comment is unpublished.
    pramod koliar · 6 months ago
    Great Script after searching all other script available in google. Can anybody help how to modify this script by specifying a folder location in local drive instead of allowing it to open the dialog box as i am actually automating the system. Thanks in advance
  • To post as a guest, your comment is unpublished.
    Pramod Koliar · 6 months ago
    Hi, great script which worked for me after trying all other script available in google. I have added few more lines which performs the text to columns operation which i want. Can anybody help me how to modify the script by specifying the folder location in local drive instead of opening the dialog box as i am actually automating the system
    . Thanks in advance
  • To post as a guest, your comment is unpublished.
    HC · 8 months ago
    Hello,

    a great article - thank you! Almost works for me.

    Here's the problem: I have a pipe-delimited csv file. I have changed the default windows delimiter (via control panel/regional settings) to "|". So, when I open the csv file with Excel, it opens, directly reads and parses the fields to columns correctly. All I have to do is to save as xls or xlsx, done. When I look at your code, that should be what the code does: It opens the csv files in a folder, saves them as xls or xlsx, and loops over that.

    Here is the problem: When I open those Excel files, the pipe delimiters are still there, nothing is parsed to the columns. This was the behavior as before my change to the pipe delimited default setting in the Windows settings. So it seems like Excel doesn't use those Windows settings. I verified this by replacing the pipe delimiters with comma delimiters in a copy of the file - of the two files, the pipe-delimited remained unparsed, the comma delimited got converted just fine.

    Any idea where that Excel-inbuilt comma delimitation can be found or changed, or whether there is a way in the code to do that? I would prefer NOT to have to do a search and replace, then save...

    Thanks, HC
    • To post as a guest, your comment is unpublished.
      Sunny · 7 months ago
      If you want to split the data into column based on the pipe delimiter in Excel, just use Text to Columns function to split data by / after coverting the csv files to xls.
  • To post as a guest, your comment is unpublished.
    Fred Maye · 11 months ago
    WHen I gave the folder name, the program said, "No files match your search." But there are 2,609 .csv files in the folder
    • To post as a guest, your comment is unpublished.
      Sunny · 10 months ago
      The code not support the separated comma csv file, are your files in this case?
  • To post as a guest, your comment is unpublished.
    ptee · 1 years ago
    I used the file multiple csv to multiple xls but get wrong xls de csv files have ; seperated info but become together in cells. How can this been solved?
    • To post as a guest, your comment is unpublished.
      Sunny · 1 years ago
      The code cannot support the separated comma csv file.
  • To post as a guest, your comment is unpublished.
    Dragos · 1 years ago
    Hi,

    Your script is great but it doesn't convert the csv separated by semicolons. Can you please post a solution for those?

    Thank you
    • To post as a guest, your comment is unpublished.
      Younes · 1 years ago
      i might be late i just got the issue where i needed to convert the semicolons CSV files and i added this to the code and it worked hope this will help someone

      Change 'Workbooks.Open Filename:=xSPath & xCSVFile' By this 'Workbooks.Open Filename:=xSPath & xCSVFile, Delimiter:=";", Local:=True'
    • To post as a guest, your comment is unpublished.
      Sunny · 1 years ago
      Sorry,here I do not have any solution, maybe you can place your question to our forum, someone else may help you. https://www.extendoffice.com/forum.html
  • To post as a guest, your comment is unpublished.
    Sathish · 1 years ago
    Thankyou so much for your excellent script for CSV to XLS. Its much more useful to my work
  • To post as a guest, your comment is unpublished.
    Matt Leonard · 1 years ago
    "Tip: If you want to convert CSV files to XLXS files, you just need to change .xls to .xlsx in the macro ActiveWorkbook.SaveAs Replace(xSPath & xCSVFile, ".csv", ".xls", vbTextCompare)."

    I tried this, and Excel could not open the resulting files. I got the following message: "Excel cannot open the file 'filename.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."

    However, the script was successful for converting to .xls.
    • To post as a guest, your comment is unpublished.
      Sunny · 1 years ago
      I did not find that problem before, thank you for your correct comment. I have corrected the tip.
  • To post as a guest, your comment is unpublished.
    Karen · 1 years ago
    I want to do the opposite - convert XLS to CSV. does this script work?
    Sub CSVtoXLS()
    'UpdatebyExtendoffice20170814
    Dim xFd As FileDialog
    Dim xSPath As String
    Dim xXLSFile As String
    Dim xWsheet As String
    Application.DisplayAlerts = False
    Application.StatusBar = True
    xWsheet = ActiveWorkbook.Name
    Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
    xFd.Title = "Select a folder:"
    If xFd.Show = -1 Then
    xSPath = xFd.SelectedItems(1)
    Else
    Exit Sub
    End If
    If Right(xSPath, 1) <> "\" Then xSPath = xSPath + "\"
    xXLSFile = Dir(xSPath & "*.xls")
    Do While xXLSFile <> ""
    Application.StatusBar = "Converting: " & xXLSFile
    Workbooks.Open Filename:=xSPath & xXLSFile
    ActiveWorkbook.SaveAs Replace(xSPath & xXLSFile, ".xls", ".csv", vbTextCompare), xlNormal
    ActiveWorkbook.Close
    Windows(xWsheet).Activate
    xXLSFile = Dir
    Loop
    Application.StatusBar = False
    Application.DisplayAlerts = True
    End Sub