Vai al contenuto principale

Come convertire in batch più file Excel in file CSV in Excel?

In Excel, possiamo convertire la cartella di lavoro in file CSV con la funzione Salva con nome, ma potresti sapere come convertire in batch più file Excel in file CSV separati? In questo articolo, introduco un codice VBA per convertire in batch tutti i file Excel in una cartella in file CSV in Excel.

Batch converte i file Excel di una cartella in file CSV con VBA

Converti fogli di cartella di lavoro in file CSV separati con Kutools per Excelbuona idea 3


Batch converte i file Excel di una cartella in file CSV con VBA

In Excel, non esiste alcuna funzione incorporata in grado di risolvere rapidamente questo lavoro tranne VBA.

1. Abilitare Excel e premere Alt + F11 chiavi aperte Microsoft Visual Basic, Applications Edition finestra.

2. Clic inserire > Moduli per creare un nuovo modulo.

3. Copia il codice sottostante e incollalo nella nuova finestra del modulo.

VBA: converte in batch i file Excel in 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. Stampa F5 chiave, seleziona la cartella contenente i file Excel che desideri convertire in file CSV nella prima finestra di dialogo.
doc batch in csv 1

5. Clic OK, quindi nella seconda finestra di dialogo popping, seleziona la cartella in cui posizionare i file CSV.
doc batch in csv 2

6. Clic OK, ora i file Excel nella cartella sono stati convertiti in file CSV e salvati in un'altra cartella.
doc batch in csv 3


Converti fogli di cartella di lavoro in file CSV separati con Kutools per Excel

Come sappiamo, possiamo solo convertire l'intera cartella di lavoro in un file CSV in Excel con la sua funzione Salva con nome. Ma a volte, vuoi convertire il singolo foglio in file CSV, in questo caso, il Cartella di lavoro divisa utilità di Kutools for Excel posso aiutarti.

Kutools for Excel, con oltre 300 funzioni utili, rende il tuo lavoro più facile. 

Dopo l'installazione Kutools per Excel, per favore fai come di seguito:(Scarica subito Kutools per Excel!)

1. Abilitare la cartella di lavoro che si desidera convertire i suoi fogli come file CSV separati, fare clic su Kutools Plus > Cartella di lavoro > Cartella di lavoro divisa.
doc batch in csv 4

2. Nel Cartella di lavoro divisa finestra di dialogo, seleziona il nome del foglio che desideri dividere (tutti i fogli sono selezionati per impostazione predefinita), seleziona Salva con nome digita, scegli CSV (Macintosh) (* .CSV) dall'elenco a discesa.
doc batch in csv 5

3. Clic Diviso per far apparire un file Sfoglia per cartella finestra di dialogo, scegli o crea una cartella in cui posizionare i file CSV.
doc batch in csv 6

4. Clic OK, ora la cartella di lavoro è stata suddivisa in file CSV separati.
doc batch in csv 7

I migliori strumenti per la produttività in ufficio

🤖 Assistente AI di Kutools: Rivoluziona l'analisi dei dati basandosi su: Esecuzione intelligente   |  Genera codice  |  Crea formule personalizzate  |  Analizzare i dati e generare grafici  |  Richiama le funzioni di Kutools...
Funzioni popolari: Trova, evidenzia o identifica i duplicati   |  Elimina righe vuote   |  Combina colonne o celle senza perdere dati   |   Round senza formula ...
Super ricerca: VLookup a criteri multipli    VLookup a valori multipli  |   VLookup su più fogli   |   Ricerca fuzzy ....
Elenco a discesa avanzato: Crea rapidamente un elenco a discesa   |  Elenco a discesa dipendente   |  Elenco a discesa a selezione multipla ....
Gestore di colonna: Aggiungi un numero specifico di colonne  |  Sposta colonne  |  Attiva/disattiva lo stato di visibilità delle colonne nascoste  |  Confronta intervalli e colonne ...
Funzionalità in primo piano: Messa a fuoco della griglia   |  Vista di progettazione   |   Grande barra delle formule    Gestore di cartelle di lavoro e fogli   |  Resource Library (Testo automatico)   |  Date picker   |  Combina fogli di lavoro   |  Crittografa/decrittografa le celle    Invia e-mail per elenco   |  Super filtro   |   Filtro speciale (filtro grassetto/corsivo/barrato...) ...
I 15 migliori set di strumenti12 Testo Strumenti (aggiungi testo, Rimuovi personaggi, ...)   |   50+ Grafico Tipi (Diagramma di Gantt, ...)   |   40+ Pratico Formule (Calcola l'età in base al compleanno, ...)   |   19 Inserimento Strumenti (Inserisci il codice QR, Inserisci immagine dal percorso, ...)   |   12 Conversione Strumenti (Numeri in parole, Conversione di valuta, ...)   |   7 Unisci e dividi Strumenti (Combina righe avanzate, Celle divise, ...)   |   ... e altro ancora

Potenzia le tue competenze di Excel con Kutools per Excel e sperimenta l'efficienza come mai prima d'ora. Kutools per Excel offre oltre 300 funzionalità avanzate per aumentare la produttività e risparmiare tempo.  Fai clic qui per ottenere la funzionalità di cui hai più bisogno...

Descrizione


Office Tab porta l'interfaccia a schede in Office e semplifica notevolmente il tuo lavoro

  • Abilita la modifica e la lettura a schede in Word, Excel, PowerPoint, Publisher, Access, Visio e Project.
  • Apri e crea più documenti in nuove schede della stessa finestra, piuttosto che in nuove finestre.
  • Aumenta la produttività del 50% e riduce ogni giorno centinaia di clic del mouse!
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