Loncat ke daftar isi utama

Bagaimana cara batch mengkonversi beberapa file CSV ke file XLS (X) di Excel?

Untuk mengonversi file CSV ke file XlS atau XLSX sangat mudah sekali bagi Anda dengan menerapkan fitur Save As. Namun, untuk mengonversi beberapa file CSV ke file XLS atau XLSX dari sebuah folder memakan waktu dengan menyimpan satu per satu secara manual. Di sini saya memperkenalkan kode makro untuk dengan cepat mengonversi semua file CSV ke file XLS (x) dari folder.

Batch mengkonversi file CSV ke file XlS (X) dengan kode makro


Batch mengkonversi file CSV ke file XlS (X) dengan kode makro

Untuk mengonversi beberapa file CSV dari satu folder ke file XLS (X), Anda dapat melakukan langkah-langkah di bawah ini:

1. Aktifkan buku kerja baru, tekan Alt + F11 kunci untuk membuka Microsoft Visual Basic untuk Aplikasi jendela, dan klik Menyisipkan > Modul. Lihat tangkapan layar:
doc batch mengkonversi cvs xls 1

Note: Pastikan semua file CSV yang ingin Anda konversi ditutup.

2. Kemudian tempelkan kode makro di bawah ini ke Modul skrip, dan tekan F5 kunci untuk menjalankan kode.

VBA: Konversi CSV ke 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. Pada dialog popping out, pilih folder tertentu yang berisi file CSV yang ingin Anda konversi. Lihat tangkapan layar:
doc batch mengkonversi cvs xls 2

4. klik OK, semua file CSV di folder yang dipilih telah diubah menjadi file XLS di dalamnya.
doc batch mengkonversi cvs xls 3

jenis: Jika Anda ingin mengonversi file CSV ke file XLSX, Anda menggunakan kode VBA di bawah ini.

VBA: Konversi file CSV ke 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

dengan cepat mengonversi atau mengekspor berbagai lembar untuk memisahkan XLS / Word / PDF atau file format lainnya sekaligus

Biasanya, Excel tidak mendukung Anda dengan opsi untuk mengekspor atau menyimpan rentang dengan cepat sebagai file CSV atau Excel. Jika Anda ingin menyimpan rentang data sebagai CSV atau buku kerja di Excel, Anda mungkin perlu menggunakan Makro VBA untuk melakukan ini atau menyalin rentang ke clipboard dan menempelkannya di buku kerja baru lalu menyimpan buku kerja sebagai CSV atau Buku Kerja. Kutools untuk Excel menambah Excel dengan Ekspor Rentang ke File utilitas untuk pengguna Excel yang ingin memproses operasi berikut dengan cepat:  Klik untuk uji coba gratis berfitur lengkap selama 30 hari!
doc mengekspor rentang sel ke file
 
Kutools for Excel: dengan lebih dari 300 add-in Excel yang praktis, gratis untuk dicoba tanpa batasan dalam 30 hari.

Artikel Relatif:

Alat Produktivitas Kantor Terbaik

馃 Kutools AI Ajudan: Merevolusi analisis data berdasarkan: Eksekusi Cerdas   |  Hasilkan Kode  |  Buat Rumus Khusus  |  Analisis Data dan Hasilkan Grafik  |  Aktifkan Fungsi Kutools...
Fitur Populer: Temukan, Sorot, atau Identifikasi Duplikat   |  Hapus Baris Kosong   |  Gabungkan Kolom atau Sel tanpa Kehilangan Data   |   Putaran tanpa Formula ...
Pencarian Super: VLookup Beberapa Kriteria    VLookup Nilai Berganda  |   VLookup di Beberapa Lembar   |   Pencarian Fuzzy ....
Daftar Drop-down Lanjutan: Buat Daftar Drop Down dengan Cepat   |  Daftar Drop Down yang Bergantung   |  Multi-pilih Drop Down List ....
Manajer Kolom: Tambahkan Jumlah Kolom Tertentu  |  Pindahkan Kolom  |  Alihkan Status Visibilitas Kolom Tersembunyi  |  Bandingkan Rentang & Kolom ...
Fitur Unggulan: Fokus Kisi   |  Tampilan Desain   |   Bar Formula Besar    Manajer Buku Kerja & Lembar   |  Perpustakaan Sumberdaya (Teks otomatis)   |  Pemetik tanggal   |  Gabungkan Lembar Kerja   |  Enkripsi/Dekripsi Sel    Kirim Email berdasarkan Daftar   |  Filter Super   |   Filter Khusus (filter tebal/miring/coret...) ...
15 Perangkat Teratas12 Teks Tools (Tambahkan Teks, Hapus Karakter, ...)   |   50 + Grafik jenis (Gantt Chart, ...)   |   40+ Praktis Rumus (Hitung usia berdasarkan ulang tahun, ...)   |   19 Insersi Tools (Masukkan Kode QR, Sisipkan Gambar dari Jalur, ...)   |   12 Konversi Tools (Angka ke Kata, Konversi Mata Uang, ...)   |   7 Gabungkan & Pisahkan Tools (Lanjutan Gabungkan Baris, Pisahkan Sel, ...)   |   ... dan banyak lagi

Tingkatkan Keterampilan Excel Anda dengan Kutools for Excel, dan Rasakan Efisiensi yang Belum Pernah Ada Sebelumnya. Kutools for Excel Menawarkan Lebih dari 300 Fitur Lanjutan untuk Meningkatkan Produktivitas dan Menghemat Waktu.  Klik Di Sini untuk Mendapatkan Fitur yang Paling Anda Butuhkan...

Deskripsi Produk


Tab Office Membawa antarmuka Tab ke Office, dan Membuat Pekerjaan Anda Jauh Lebih Mudah

  • Aktifkan pengeditan dan pembacaan tab di Word, Excel, PowerPoint, Publisher, Access, Visio, dan Project.
  • Buka dan buat banyak dokumen di tab baru di jendela yang sama, bukan di jendela baru.
  • Meningkatkan produktivitas Anda sebesar 50%, dan mengurangi ratusan klik mouse untuk Anda setiap hari!
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