Gå til hovedindhold

Hvordan batchkonverteres flere Excel-filer til CSV-filer i Excel?

I Excel kan vi konvertere projektmappen til CSV-fil med funktionen Gem som, men kunne du vide, hvordan du batchkonverterer flere Excel-filer til separate CSV-filer? I denne artikel introducerer jeg en VBA-kode til batchkonvertering af alle Excel-filer i en mappe til CSV-filer i Excel.

Batchkonverter Excel-filer i en mappe til CSV-filer med VBA

Konverter ark med projektmappe til separate CSV-filer med Kutools til Excelgod idé3


Batchkonverter Excel-filer i en mappe til CSV-filer med VBA

I Excel er der ingen indbygget funktion, der kan løse dette job hurtigt undtagen VBA.

1. Aktivér Excel, og tryk på Alt + F11 tasterne åbnes Microsoft Visual Basic til applikationer vindue.

2. klik indsatte > Moduler for at oprette et nyt modul.

3. Kopier nedenstående kode og indsæt dem i det nye modulvindue.

VBA: Batchkonvertere Excel-filer til CSV

Sub WorkbooksSaveAsCsvToFolder()

'UpdatebyExtendoffice20181031

Dim xObjWB As Workbook

Dim xObjWS As Worksheet

Dim xStrEFPath As String

Dim xStrEFFile As String

Dim xObjFD As FileDialog

Dim xObjSFD As FileDialog

Dim xStrSPath As String

Dim xStrCSVFName As String

Dim xS  As String

    Application.ScreenUpdating = False

    Application.EnableEvents = False

    Application.Calculation = xlCalculationManual

    Application.DisplayAlerts = False

    On Error Resume Next

Set xObjFD = Application.FileDialog(msoFileDialogFolderPicker)

    xObjFD.AllowMultiSelect = False

    xObjFD.Title = "Kutools for Excel - Select a folder which contains Excel files"

    If xObjFD.Show <> -1 Then Exit Sub

    xStrEFPath = xObjFD.SelectedItems(1) & "\"

    Set xObjSFD = Application.FileDialog(msoFileDialogFolderPicker)

 
    xObjSFD.AllowMultiSelect = False

    xObjSFD.Title = "Kutools for Excel - Select a folder to locate CSV files"

    If xObjSFD.Show <> -1 Then Exit Sub

    xStrSPath = xObjSFD.SelectedItems(1) & "\"


    xStrEFFile = Dir(xStrEFPath & "*.xls*")


    Do While xStrEFFile <> ""

       xS = xStrEFPath & xStrEFFile

        Set xObjWB = Application.Workbooks.Open(xS)

        xStrCSVFName = xStrSPath & Left(xStrEFFile, InStr(1, xStrEFFile, ".") - 1) & ".csv"

        xObjWB.SaveAs Filename:=xStrCSVFName, FileFormat:=xlCSV

        xObjWB.Close savechanges:=False

        xStrEFFile = Dir

  Loop

    Application.Calculation = xlCalculationAutomatic

    Application.EnableEvents = True

    Application.ScreenUpdating = True

    Application.DisplayAlerts = True

End Sub

4. Trykke F5 nøgle, vælg mappen, der indeholder de Excel-filer, du vil konvertere til CSV-filer i den første poppende dialog.
doc-batch til csv 1

5. klik OK, vælg derefter i den anden poppedialog den mappe, der skal placere CSV-filerne.
doc-batch til csv 2

6. klik OK, nu er Excel-filerne i mappen konverteret til CSV-filer og gemt i en anden mappe.
doc-batch til csv 3


Konverter ark med projektmappe til separate CSV-filer med Kutools til Excel

Som vi vidste, kan vi kun konvertere hele projektmappen til en CSV-fil i Excel med dens Gem som-funktion. Men i nogle gange vil du konvertere det enkelte ark til CSV-fil, i dette tilfælde den Opdelt arbejdsbog nytte af Kutools til Excel kan hjælpe dig.

Kutools til Excel, med mere end 300 praktiske funktioner, der gør dine job lettere. 

Efter installation Kutools til Excel, gør venligst som nedenfor:(Gratis download Kutools til Excel nu!)

1. Aktivér projektmappe, du vil konvertere dens ark som separate CSV-filer, klik på Kutools Plus > Workbook > Opdelt arbejdsbog.
doc-batch til csv 4

2. i Opdelt arbejdsbog dialog, skal du kontrollere det arknavn, du vil opdele (alle ark er markeret som standard), skal du kontrollere Gem som skriv, vælg CSV (Macintosh) (* .CSV) fra rullelisten.
doc-batch til csv 5

3. klik Dele at poppe ud a Gennemse for mappe dialog, skal du vælge eller oprette en mappe for at placere CSV-filerne.
doc-batch til csv 6

4. klik OK, nu er projektmappen opdelt som separate CSV-filer.
doc-batch til csv 7

Bedste kontorproduktivitetsværktøjer

🤖 Kutools AI Aide: Revolutionér dataanalyse baseret på: Intelligent udførelse   |  Generer kode  |  Opret brugerdefinerede formler  |  Analyser data og generer diagrammer  |  Aktiver Kutools funktioner...
Populære funktioner: Find, fremhæv eller identificer dubletter   |  Slet tomme rækker   |  Kombiner kolonner eller celler uden at miste data   |   Runde uden formel ...
Super opslag: VLookup med flere kriterier    Multiple Value VLookup  |   VOpslag på tværs af flere ark   |   Fuzzy Lookup ....
Avanceret rulleliste: Opret hurtigt rulleliste   |  Afhængig rulleliste   |  Multivælg rulleliste ....
Column Manager: Tilføj et bestemt antal kolonner  |  Flyt kolonner  |  Skift synlighedsstatus for skjulte kolonner  |  Sammenlign områder og kolonner ...
Fremhævede funktioner: Grid fokus   |  Designvisning   |   Stor Formel Bar    Arbejdsbog & Ark Manager   |  Ressourcebibliotek (Autotekst)   |  Datovælger   |  Kombiner regneark   |  Krypter/Dekrypter celler    Send e-mails efter liste   |  Superfilter   |   Specielt filter (filter fed/kursiv/gennemstreget...) ...
Top 15 værktøjssæt12 tekst Værktøjer (tilføje tekst, Fjern tegn, ...)   |   50 + Chart Typer (Gantt kort, ...)   |   40+ Praktisk formler (Beregn alder baseret på fødselsdag, ...)   |   19 Indsættelse Værktøjer (Indsæt QR-kode, Indsæt billede fra sti, ...)   |   12 Konvertering Værktøjer (Tal til ord, Valutaomregning, ...)   |   7 Flet og del Værktøjer (Avancerede kombinere rækker, Opdel celler, ...)   |   ... og mere

Overlad dine Excel-færdigheder med Kutools til Excel, og oplev effektivitet som aldrig før. Kutools til Excel tilbyder over 300 avancerede funktioner for at øge produktiviteten og spare tid.  Klik her for at få den funktion, du har mest brug for...

Beskrivelse


Fanen Office bringer en grænseflade til et kontor med Office, og gør dit arbejde meget lettere

  • Aktiver redigering og læsning af faner i Word, Excel, PowerPoint, Publisher, Access, Visio og Project.
  • Åbn og opret flere dokumenter i nye faner i det samme vindue snarere end i nye vinduer.
  • Øger din produktivitet med 50 % og reducerer hundredvis af museklik for dig hver dag!
Comments (37)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Thank you, lifesaver, I have no coding experience but this seems to work for my purposes perfectly.

Is it possible to set the directory for the read xls and write csv so that you don't have to select it each time? My files are being written to the same location each day automatically and I'm trying to automate this conversion to csv as much as I can.

Thanks,
This comment was minimized by the moderator on the site
This is a great peace of coding, but I just realised that it is inverting the dates for me. (we are in UK) and when the date shows 23/03/78 in the CSV the date comes out as 3/23/78.

Is doesn't happen to all lives. Eg if the date was showing 1/2/11 it would stay the same. But if it was 01/02/11 it would chnage to 02/01/11

Any suggestions?
This comment was minimized by the moderator on the site
Batch script not accept unicode character in file name or in work sheet. I've changed
xObjWB.SaveAs Filename:=xStrCSVFName, FileFormat:=[b]xlCSV[/b]


to

xObjWB.SaveAs Filename:=xStrCSVFName, FileFormat:=[b]xlCSVUTF8[/b]. But [b]xlCSVUTF8[/b] seems not supported in older excel version (before 2016)


Batch script not support files in recursive folders too.
This comment was minimized by the moderator on the site
Hallo,

ich habe den VBA-Code vor einem Jahr ohne Probleme angewendet. Jetzt funktioniert es nicht mehr.
Es gibt einen Laufzeitfehler 1004 mit dem Hinweis: "Die Methode 'calculation' für das Objekt '_Application' ist fehlgeschlagen."

Debuggen verweist auf die Zeile "Application.Calculation = xlCalculationManual".

Ich würde mich sehr freuen, wenn jemand weiterhelfen könnte.

LG, Max
This comment was minimized by the moderator on the site
Hi, Gast, pleae check if the code you copied is correct firstly, there is no "_" in the code. If you have checked all code is correct, you can remove the code line
Application.Calculation = xlCalculationManual then try again. Please notice that there are two lines Application.Calculation = xlCalculationManual in the code.
This comment was minimized by the moderator on the site
Hallo,

vor einem Jahr habe ich den VBA-Code ohne Probleme ausgeführt. Heute wollte ich es nochmal versuchen, leider gibt es einen Laufzeitfehler 1004 mit dem Hinweis
"Die Methode 'Calculation' ist für Objekt '_Application' fehlgeschlagen."

Debuggen verweist auf folgende Zeile:
Application.Calculation = xlCalculationManual

Kann jemand weiterhelfen?

LG, Max
This comment was minimized by the moderator on the site
Hi,
I'm facing some problems when using the script
Ho can I change the delimiter in the script because the delimiter in csv output is in comma (,)
I need the delimiter not in comma because my datasets consist a lot of commas.


Thank you
This comment was minimized by the moderator on the site
Ajouter Local:=True à cette ligne:
xObjWB.SaveAs Filename:=xStrCSVFName, FileFormat:=xlCSV, Local:=True

Permet de prendre le séparateur de votre système, moi c'est point-virgule ;
This comment was minimized by the moderator on the site
Hi, How can i change the delimiter ?
In the script above, the delimiter is comma (,).
Thank you :D
This comment was minimized by the moderator on the site
2019버전입니다.
게시글 그대로 실행해봤지만 아무것도 일어나지 않았습니다 ..
This comment was minimized by the moderator on the site
Hi, YOY, I have tested the VBA in Professional Plus Excel 2019, it works smoothly and correctly. Should you give me more details about your files, such as detailed verison, the contents of files you want to convert?
This comment was minimized by the moderator on the site
Bom Dia!!

muito top esse codigo, porem estou com o problema abaixo

Tem como salvar em formato "CSV (separado por vírgulas) (*.csv)", pois ao executar esse código meus arquivos ficam com "," no formato que eu preciso eles não ficam com essa vírgula
This comment was minimized by the moderator on the site
Same issue with me. Running latest office 365 but nothing happens after setting the two folders dialog boxes.
This comment was minimized by the moderator on the site
Hi, Doc SJ, thanks for your reminder, I have check the VBA code, it has some issues in Office 365, now I have updated the VBA, please try it again.
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