Consejo: Otros idiomas son traducidos por Google. Puedes visitar el English versión de este enlace.
Iniciar sesión
x
or
x
x
Suscríbete
x

or

¿Cómo convertir por lotes múltiples archivos CSV a archivos XLS (X) en Excel?

Convertir un archivo CSV a un archivo XLS o XLSX es muy fácil para usted al aplicar la función Guardar como. Sin embargo, convertir varios archivos CSV a archivos XLS o XLSX desde una carpeta consume mucho tiempo al guardar uno por uno manualmente. Aquí presento un código de macro para convertir por lotes rápidamente todos los archivos CSV a archivos XLS (x) desde una carpeta.

Lote convertir archivos CSV a archivos XLS (X) con código de macro

Ficha Office Habilite la edición y navegación con pestañas en Office y haga su trabajo mucho más fácil ...
Kutools para Excel: la mejor herramienta de productividad de Office resolverá la mayoría de sus problemas de Excel
  • Texto automático: Cree sus gráficos, imágenes, celdas, fórmulas complejas y reutilizar ellos rápidamente en el futuro.
  • Más de características de texto 20: Extraer número de la cadena de texto; Extraer o eliminar parte de los textos; Convertir números y monedas a palabras en inglés ...
  • Herramientas de fusión: Múltiples libros de trabajo y hojas en uno; Fusionar múltiples celdas / filas / columnas y guardar datos; Combinar filas duplicadas y sumar ...
  • Herramientas divididas: Dividir datos en varias hojas en función del valor; Un libro de trabajo para múltiples archivos Excel, PDF o CSV; De una columna a varias columnas ...
  • Saltar pasta Filas ocultas / filtradas; Cuenta y suma por color de fondo; Crear lista de correo y Enviar correos electrónicos por el valor de la celda...
  • Súper filtro: Cree esquemas de filtro avanzados y aplique a cualquier hoja; Tipo de Propiedad por semana, día, frecuencia y más; Filtrar por negrita, fórmulas, comentario ...
  • Más de potentes funciones de 300; Funciona con Office 2007-2019 y 365; Soporta todos los idiomas; Fácil despliegue en compañía; Funciones completas de prueba gratuita de 60-day.

Lote convertir archivos CSV a archivos XLS (X) con código de macro


Para convertir varios archivos CSV de una carpeta a archivos XLS (X), puede hacer lo siguiente:

Kutools for Excel, con más de 120 funciones prácticas, hace que sus trabajos sean más fáciles.

1. Habilite un nuevo libro de trabajo, presione Alt + F11 llaves para abrir Microsoft Visual Basic para aplicaciones ventana y haga clic recuadro > Módulo. Ver captura de pantalla:
doc batch convert cvs xls 1

Nota: Asegúrese de que todos los archivos CSV que desea convertir estén cerrados.

2. A continuación, pegue el código de macro debajo del Módulo secuencia de comandos y prensa F5 clave para ejecutar el código.

VBA: convierte CSV a 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. En el cuadro de diálogo emergente, seleccione la carpeta especificada que contiene los archivos CSV que desea convertir. Ver captura de pantalla:
doc batch convert cvs xls 2

4. Hacer clic OK, todos los archivos CSV en la carpeta seleccionada se han convertido a archivos XLS.
doc batch convert cvs xls 3

Tip: Si desea convertir archivos CSV a archivos XLSX, use el siguiente código VBA.

VBA: convierte archivos CSV a 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


buenoExportar rango a archivo

Kutools para Excels Exportar rango a la función de archivo puede exportar o guardar un rango para separar el archivo como
libro de trabajo, pdf, texto, csv o texto.
Haz click Empresa > Import / Export > Exportar rango a archivo.
doc exportar rango de celdas al archivo

Artículos relativos


Kutools for Excel: la mejor herramienta de productividad de Office aumenta su productividad en un 80%

  • Super Formula Bar (edite fácilmente varias líneas de texto y fórmula); Diseño de lectura (lee y edita fácilmente un gran número de celdas); Pegar en rango filtrado...
  • Combinar celdas / filas / columnas y mantener datos; Contenido de celdas divididas; Combinar filas duplicadas y suma / promedio... Prevenir células duplicadas; Comparar rangos...
  • Seleccione Duplicado o Único Filas; Seleccionar filas en blanco (todas las celdas están vacías); Super Find y Fuzzy Find en muchos libros de trabajo; Selección aleatoria ...
  • Copia exacta Celdas múltiples sin cambiar la referencia de fórmula; Crear referencias automáticamente a múltiples hojas; Insertar viñetas, Casillas de verificación y más ...
  • Fórmulas favoritas e insertadas rápidamente, Gamas, cuadros y cuadros; Cifrar celdas con contraseña Crear una lista de correo y enviar correos electrónicos ...
  • Extracto del texto, Agregar texto, Eliminar por posición, Eliminar espacio; Crear e imprimir subtotales de paginación; Convertir entre contenido de celdas y comentarios...
  • Súper filtro (guardar y aplicar esquemas de filtro a otras hojas); Clasificación avanzada por mes / semana / día, frecuencia y más; Filtro especial por negrita, cursiva ...
  • Combinar libros de trabajo y hojas de trabajo; Combinar tablas basadas en columnas clave; Dividir datos en varias hojas; Conversión por lotes xls, xlsx y PDF...
  • Más de potentes funciones de 300. Funciona con Office 2007-2019 y 365. Soporta todos los idiomas. Fácil despliegue en compañía. Funciones completas de prueba gratuita de 60-day.
pestaña kte 201905

Office Tab lleva la interfaz con pestañas a Office y hace que su trabajo sea mucho más fácil

  • Habilitar la edición y lectura con pestañas en Word, Excel, PowerPoint, Editor, Acceso, Visio y Proyecto.
  • Abra y cree varios documentos en nuevas pestañas de la misma ventana, en lugar de en nuevas ventanas.
  • ¡Aumenta tu productividad en un 50% y reduce cientos de clics de ratón por ti todos los días!
fondo 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 · 24 days 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.
    KXP · 2 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.
    Sam · 2 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 · 3 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 · 3 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 · 1 months ago
        no you haven't. it still says xls in both versions.
  • To post as a guest, your comment is unpublished.
    pramod koliar · 5 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 · 5 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 · 7 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 · 6 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 · 10 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 · 11 months 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