Ga naar hoofdinhoud

Hoe converteer ik meerdere CSV-bestanden batchgewijs naar XLS (X) -bestanden in Excel?

Het converteren van een CSV-bestand naar XlS- of XLSX-bestand is heel eenvoudig voor u door de functie Opslaan als toe te passen. Het is echter tijdrovend om meerdere CSV-bestanden vanuit een map naar XLS- of XLSX-bestanden te converteren door ze een voor een handmatig op te slaan. Hier introduceer ik een macrocode om snel alle CSV-bestanden vanuit een map naar XLS (x) -bestanden te converteren.

Batch converteer CSV-bestanden naar XlS (X) -bestanden met macrocode


Batch converteer CSV-bestanden naar XlS (X) -bestanden met macrocode

Om meerdere CSV-bestanden van één map naar XLS (X) -bestanden te converteren, kunt u de onderstaande stappen uitvoeren:

1. Activeer een nieuwe werkmap, druk op Alt + F11 sleutels om te openen Microsoft Visual Basic voor toepassingen venster en klik Invoegen > Module. Zie screenshot:
doc batch converteren cvs xls 1

Note: Zorg ervoor dat alle CSV-bestanden die u wilt converteren, zijn gesloten.

2. Plak vervolgens onderstaande macrocode in het Module script en druk op F5 sleutel om de code uit te voeren.

VBA: converteer CSV naar 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. Selecteer in het pop-outvenster de opgegeven map met de CSV-bestanden die u wilt converteren. Zie screenshot:
doc batch converteren cvs xls 2

4. klikken OK, zijn alle CSV-bestanden in de geselecteerde map geconverteerd naar XLS-bestanden erin.
doc batch converteren cvs xls 3

Tip: Als u CSV-bestanden naar XLSX-bestanden wilt converteren, gebruikt u onderstaande VBA-code.

VBA: converteer CSV-bestanden naar 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", ".xlsx", vbTextCompare), xlWorkbookDefault
        ActiveWorkbook.Close
        Windows(xWsheet).Activate
        xCSVFile = Dir
    Loop
    Application.StatusBar = False
    Application.DisplayAlerts = True
End Sub

converteer of exporteer snel een reeks van een blad om XLS / Word / PDF- of andere formaatbestanden in één keer te scheiden

Normaal gesproken ondersteunt Excel u niet met een optie om snel een bereik te exporteren of op te slaan als een CSV- of Excel-bestand. Als u een gegevensbereik als CSV of werkmap in Excel wilt opslaan, moet u mogelijk een VBA-macro gebruiken om dit te doen of om het bereik naar het klembord te kopiëren en in een nieuwe werkmap te plakken en vervolgens de werkmap op te slaan als CSV of Werkboek. Kutools for Excel vergroot Excel met Bereik exporteren naar bestand hulpprogramma voor Excel-gebruikers die de volgende bewerkingen snel willen verwerken:  Klik voor een gratis proefperiode van 30 dagen met volledige functionaliteit!
doc celbereik exporteren naar bestand
 
Kutools for Excel: met meer dan 300 handige Excel-invoegtoepassingen, gratis te proberen zonder beperking in 30 dagen.

Relatieve artikelen:

Beste Office-productiviteitstools

🤖 Kutools AI-assistent: Een revolutie teweegbrengen in de data-analyse op basis van: Intelligente uitvoering   |  Genereer code  |  Aangepaste formules maken  |  Analyseer gegevens en genereer grafieken  |  Roep Kutools-functies aan...
Populaire functies: Zoek, markeer of identificeer duplicaten   |  Verwijder lege rijen   |  Combineer kolommen of cellen zonder gegevens te verliezen   |   Ronde zonder formule ...
Super opzoeken: Meerdere criteria VLookup    VLookup met meerdere waarden  |   VOpzoeken over meerdere bladen   |   Fuzzy opzoeken ....
Geavanceerde vervolgkeuzelijst: Maak snel een vervolgkeuzelijst   |  Afhankelijke vervolgkeuzelijst   |  Multi-select vervolgkeuzelijst ....
Kolom Beheerder: Voeg een specifiek aantal kolommen toe  |  Kolommen verplaatsen  |  Schakel de zichtbaarheidsstatus van verborgen kolommen in  |  Vergelijk bereiken en kolommen ...
Uitgelichte functies: Raster focus   |  Ontwerpweergave   |   Grote formulebalk    Werkmap- en bladbeheer   |  resource Library (Auto-tekst)   |  Datumkiezer   |  Combineer werkbladen   |  Cellen coderen/decoderen    Stuur e-mails per lijst   |  Super filter   |   Speciaal filter (filter vet/cursief/doorhalen...) ...
Top 15 gereedschapsets12 Tekst Tools (toe te voegen tekst, Tekens verwijderen, ...)   |   50+ tabel Types (Gantt Chart, ...)   |   40+ Praktisch Formules (Bereken leeftijd op basis van verjaardag, ...)   |   19 Invoeging Tools (QR-code invoegen, Afbeelding invoegen vanaf pad, ...)   |   12 Camper ombouw Tools (Getallen naar woorden, Currency Conversion, ...)   |   7 Samenvoegen en splitsen Tools (Geavanceerd Combineer rijen, Gespleten cellen, ...)   |   ... en meer

Geef uw Excel-vaardigheden een boost met Kutools voor Excel en ervaar efficiëntie als nooit tevoren. Kutools voor Excel biedt meer dan 300 geavanceerde functies om de productiviteit te verhogen en tijd te besparen.  Klik hier om de functie te krijgen die u het meest nodig heeft...

Omschrijving


Office-tabblad Brengt een interface met tabbladen naar Office en maakt uw werk veel gemakkelijker

  • Schakel bewerken en lezen met tabbladen in Word, Excel, PowerPoint in, Publisher, Access, Visio en Project.
  • Open en maak meerdere documenten in nieuwe tabbladen van hetzelfde venster in plaats van in nieuwe vensters.
  • Verhoogt uw productiviteit met 50% en vermindert honderden muisklikken voor u elke dag!
Comments (41)
Rated 5 out of 5 · 1 ratings
This comment was minimized by the moderator on the site
Realmente me funcionó, muchas gracias!
Rated 5 out of 5
This comment was minimized by the moderator on the site
Thanks for this macro code! It works and converts my csv's to xlsx and saves me time. The only problem I have is that the column name in cell A1 is gone.
I have to add this back to all the xlsx files because this is needed for further scripts I run on the xlsx files.
This comment was minimized by the moderator on the site
Hi, Cyril, I have test the code again, the column name in A1 is still saved in the xlsx files.
This comment was minimized by the moderator on the site
Not working. Copied same code.. Pop up comes to select csv but even though there are csv files in the folder, non appears in the browse list. any reason why?
This comment was minimized by the moderator on the site
Buenos dias compañeros

Adiciona a lo que hace el script, quisiera poder convertir inmediatamente el texto en columnas, por la opción que no es delimitado por ningún tipo de caracter, adicional los tamaños de las columnas son diferentes. Vale la pena aclarar que si tomo cada archivo por separado y le aplico la opción de texto en columnas, bajo esa opción los puedo convertir sin problemas, abriéndolos uno por uno, pero si grabo esa macro y le aplico la misma macro a todos, inclusive usando la opción de "USAR REFERENCIAS RELATIVAS", no hace el proceso bien, porque el graba las posiciones de la delimitación del archivo que uso de ejemplo, pero necesito que lo aplique nuevo a cada archivo, es decir, como si abriera cada archivo nuevo y le hiciera manualmente la opción de delimitación y no aplique los valores de ubicación de las columnas identificados en el archivo ejemplo.

Ya inserte esa opcion en este archivo, sin embargo pasa lo que indico en la lineas arriba, solo requiero saber como puedo hacer para aplicar la conversion a cada archivo, aplicando la delimitacion del campo como su fuera un archivo nuevo.


Workbooks.Open Filename:=xSPath & xCSVFile
ActiveWorkbook.SaveAs Replace(xSPath & xCSVFile, ".csv", ".xlsx", vbTextCompare), xlWorkbookDefault

ESTA PARTE ES LA QUE AGREGUE APLICANDO EL FORMATO DEL TEXTO A COLUMNAS

StartRow:=1, DataType:=xlFixedWidth, FieldInfo:=Array(Array(0, 1), Array(18 _
, 1), Array(38, 1)), TrailingMinusNumbers:=True
ActiveCell.Cells.Select
ActiveCell.Cells.EntireColumn.AutoFit
ActiveCell.Offset(1, 0).Range("A1").Select
ActiveWorkbook.Save

HASTA AQUI AGREGUE YO

ActiveWorkbook.Close
Windows(xWsheet).Activate
xCSVFile = Dir

Loop
Application.StatusBar = False
Application.DisplayAlerts = True
End Sub

No se si me hago explicar bien, pero es mi problema.
This comment was minimized by the moderator on the site
yes it's not work.
This comment was minimized by the moderator on the site
How would I incorporate code into the XLSX batch file routine to semicolon separate the data into separate columns? The code shared converts the file from a .csv to a .xlsx, but it doesn't separate the data into separate columns.
This comment was minimized by the moderator on the site
This is working for me, but the file extension is not changing. Any tips?
This comment was minimized by the moderator on the site
I had the same problem. If your source file has an extention in capital letters (.CSV) it doesnt work. Just replace .csv to .CSV in the code in line 22 and then it should work. Well, at least for me it did.
This comment was minimized by the moderator on the site
Same for me -- all files remain .csv.
This comment was minimized by the moderator on the site
All csv files you choose have been save as new excel files, the original files (csv) do not change, there are new excel files with same contents existing.
This comment was minimized by the moderator on the site
I get an error "Object variable or with block variable not set" for this line:
xFd.Title = "/Users/[my.name]/Documents/[myFolder]" >> this is the path of a particular folder on my computer where I'm doing the conversion (the folder has a bunch of csv files inside)

Am I doing something wrong here?
This comment was minimized by the moderator on the site
You have an error on line 22 of the csv to xlsx
With Error - ActiveWorkbook.SaveAs Replace(xSPath & xCSVFile, ".csv", ".xls", vbTextCompare), xlWorkbookDefault
Corrected - ActiveWorkbook.SaveAs Replace(xSPath & xCSVFile, ".csv", ".xslx", vbTextCompare), xlWorkbookDefault
This comment was minimized by the moderator on the site
Thanks for your reminder, I have updated it, thanks again.
This comment was minimized by the moderator on the site
great article. How can I, save all the converted files in a new location? Can you please update the code and send it to me. Like allowing the user to choose his destination folder.


Thanks
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations