Skip to main content

Conas baisc comhaid iolracha CSV a thiontú go comhaid XLS (X) in Excel?

Tá sé an-éasca duit comhad CSV a thiontú go comhad XlS nó XLSX tríd an ngné Save As a chur i bhfeidhm. Tógann sé go leor ama, áfach, chun comhaid CSV iolracha a thiontú go comhaid XLS nó XLSX ó fhillteán trí shábháil ceann ar cheann de láimh. Seo a thugann mé macra-chód isteach chun gach comhad CSV a thiontú go comhaid XLS (x) ó fhillteán go tapa.

Tiontaigh baisc comhaid CSV go comhaid XlS (X) le macra-chód


Tiontaigh baisc comhaid CSV go comhaid XlS (X) le macra-chód

Chun comhaid CSV iolracha a thiontú ó fhillteán amháin go comhaid XLS (X), is féidir leat déanamh mar atá thíos céimeanna:

1. Cumasaigh leabhar oibre nua, brúigh Alt + F11 eochracha le hoscailt Microsoft Visual Basic d’Fheidhmchláir fuinneog, agus cliceáil Ionsáigh > Modúil. Féach an pictiúr:
baisc doc tiontú cvs xls 1

nótaí: Déan cinnte go bhfuil gach comhad CSV a theastaíonn uait a thiontú dúnta.

2. Ansin greamaigh thíos an cód macra chuig an Modúil script, agus brúigh F5 eochair chun an cód a rith.

VBA: Tiontaigh CSV go 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. Sa dialóg popping amach, roghnaigh an fillteán sonraithe ina bhfuil na comhaid CSV a theastaíonn uait a thiontú. Féach an pictiúr:
baisc doc tiontú cvs xls 2

4. cliceáil OK, athraíodh na comhaid CSV go léir san fhillteán roghnaithe go comhaid XLS ann.
baisc doc tiontú cvs xls 3

Leid: Más mian leat comhaid CSV a thiontú go comhaid XLSX, úsáideann tú thíos cód VBA.

VBA: Tiontaigh comhaid CSV go 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

raon bileog a thiontú nó a easpórtáil go tapa chun comhaid XLS / Word / PDF nó formáid eile a scaradh in aon uair amháin

De ghnáth, ní thacaíonn Excel leat le rogha raon a easpórtáil nó a shábháil go tapa mar chomhad CSV nó Excel. Más mian leat raon sonraí a shábháil mar CSV nó mar leabhar oibre in Excel, b’fhéidir go mbeidh ort Macra VBA a úsáid chun é seo a dhéanamh nó chun an raon a chóipeáil go gearrthaisce agus é a ghreamú i leabhar oibre nua agus ansin an leabhar oibre a shábháil mar CSV nó Leabhar Oibre. Kutools le haghaidh Excel méadaíonn Excel le Raon Easpórtála go Comhad fóntais d’úsáideoirí Excel ar mian leo na hoibríochtaí seo a leanas a phróiseáil go tapa :  Cliceáil le haghaidh triail iomlán 30 lá le feiceáil saor in aisce!
doc raon cille a onnmhairiú go comhad
 
Kutools for Excel: le níos mó ná 300 breiseán áisiúil Excel, saor in aisce le triail gan aon teorannú i 30 lá.

Ailt Choibhneasta:

Uirlisí Táirgiúlachta Oifige is Fearr

🤖 Kutools AI Aide: anailís sonraí a réabhlóidiú bunaithe ar: Forghníomhú Chliste   |  Gin Cód  |  Cruthaigh Foirmlí Saincheaptha  |  Anailís a dhéanamh ar Sonraí agus Cairteacha a Ghin  |  Feidhmeanna Kutools a agairt...
Gnéithe Coitianta: Faigh, Aibhsigh nó Aithnigh Dúblaigh   |  Scrios Sraitheanna Bána   |  Comhcheangail Colúin nó Cealla gan Sonraí a Chailleadh   |   Babhta gan Foirmle ...
Cuardaigh Super: Ilchritéir VLookup    VLookup Illuachanna  |   VLookup Trasna Ilbhileoga   |   Amharc doiléir ....
Liosta anuas Casta: Go tapa Cruthaigh Liosta Anuas   |  Liosta anuas Cleithiúnach   |  Liosta Buail Isteach Ilroghnacha ....
Bainisteoir Colún: Cuir Líon Sonrach Colún leis  |  Colúin Bog  |  Scoránaigh Stádas Infheictheachta na gColún Ceilte  |  Déan comparáid idir Raonta & Colúin ...
Gnéithe Réadmhaoin: Fócas Eangaí   |  Amharc Dearaidh   |   Barra Mór na Foirmle    Leabhar Oibre & Bainisteoir Bileog   |  Leabharlann Acmhainní (Uaththéacs)   |  Piocálaí Dáta   |  Comhcheangail Bileoga Oibre   |  Criptigh/Díchriptigh Cealla    Seol Ríomhphost trí Liosta   |  Scagaire Super   |   Scagaire Speisialta (scagaire trom/iodálach/stailc tríd...) ...
Barr 15 Uirlisí12 Téacs uirlisí (Cuir Téacs, Bain Carachtair,...)   |   50 + Cairt cineálacha (Cairt Gantt,...)   |   40+ Praiticiúil Foirmlí (Ríomh aois bunaithe ar lá breithe,...)   |   19 Insertion uirlisí (Cuir isteach Cód QR, Ionsáigh Pictiúr ón gCosán,...)   |   12 Tiontú uirlisí (Uimhreacha le Focail, Comhshó Airgeadra,...)   |   7 Cumaisc & Scoilt uirlisí (Sraitheanna Comhcheangail Casta, Cealla Scoilt,...)   |   ... agus eile

Supercharge Do Scileanna Excel le Kutools le haghaidh Excel, agus Éifeachtúlacht Taithí Cosúil Ná Roimhe. Kutools le haghaidh Excel Tairiscintí Níos mó ná 300 Ardghnéithe chun Táirgiúlacht a Treisiú agus Sábháil Am.  Cliceáil anseo chun an ghné is mó a theastaíonn uait a fháil ...

Tuairisc


Tugann Tab Oifige comhéadan Tabbed chuig Office, agus Déan Do Obair i bhfad Níos Éasca

  • Cumasaigh eagarthóireacht agus léamh tabbed i Word, Excel, PowerPoint, Foilsitheoir, Rochtain, Visio agus Tionscadal.
  • Oscail agus cruthaigh cáipéisí iolracha i gcluaisíní nua den fhuinneog chéanna, seachas i bhfuinneoga nua.
  • Méadaíonn do tháirgiúlacht 50%, agus laghdaíonn sé na céadta cad a tharlaíonn nuair luch duit gach lá!
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