Note: The other languages of the website are Google-translated. Back to English
로그인  \/ 
x
or
x
REGISTER  \/ 
x

or

Excel에서 여러 CSV 파일을 XLS (X) 파일로 일괄 변환하는 방법은 무엇입니까?

CSV 파일을 XlS 또는 XLSX 파일로 변환하는 것은 다른 이름으로 저장 기능을 적용하여 매우 쉽습니다. 그러나 여러 CSV 파일을 폴더에서 XLS 또는 XLSX 파일로 변환하려면 하나씩 수동으로 저장하면 시간이 많이 걸립니다. 여기에서는 모든 CSV 파일을 폴더에서 XLS (x) 파일로 빠르게 일괄 변환하는 매크로 코드를 소개합니다.

매크로 코드를 사용하여 CSV 파일을 XlS (X) 파일로 일괄 변환


매크로 코드를 사용하여 CSV 파일을 XlS (X) 파일로 일괄 변환

여러 CSV 파일을 한 폴더에서 XLS (X) 파일로 변환하려면 다음 단계를 수행하십시오.

1. 새 통합 문서를 활성화하고 Alt + F11 여는 열쇠 응용 프로그램 용 Microsoft Visual Basic 창을 클릭 한 다음 끼워 넣다 > 모듈. 스크린 샷보기 :
문서 일괄 변환 cvs xls 1

주의 사항: 변환하려는 모든 CSV 파일이 닫혀 있는지 확인하십시오.

2. 그런 다음 매크로 코드 아래에 붙여 넣습니다. 모듈 스크립트를 누르고 F5 코드를 실행하는 키입니다.

VBA : CSV를 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. 팝업 대화 상자에서 변환하려는 CSV 파일이 포함 된 지정된 폴더를 선택합니다. 스크린 샷보기 :
문서 일괄 변환 cvs xls 2

4. 클릭 OK, 선택한 폴더의 모든 CSV 파일이 XLS 파일로 변환되었습니다.
문서 일괄 변환 cvs xls 3

: CSV 파일을 XLSX 파일로 변환하려면 아래 VBA 코드를 사용합니다.

VBA : CSV 파일을 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

시트 범위를 한 번에 별도의 XLS / Word / PDF 또는 기타 형식 파일로 빠르게 변환하거나 내 보냅니다.

일반적으로 Excel은 범위를 CSV 또는 Excel 파일로 빠르게 내보내거나 저장하는 옵션을 지원하지 않습니다. 데이터 범위를 Excel의 CSV 또는 통합 문서로 저장하려면 VBA 매크로를 사용하여이를 수행하거나 범위를 클립 보드에 복사하여 새 통합 문서에 붙여 넣은 다음 통합 문서를 CSV 또는 학습장. Excel 용 Kutools Excel을 범위를 파일로 내보내기 다음 작업을 빠르게 처리하려는 Excel 사용자를위한 유틸리티 :  30 일 전체 기능을 무료로 사용하려면 클릭하세요!
doc 셀 범위를 파일로 내보내기
 
Excel 용 Kutools : 300 개 이상의 편리한 Excel 추가 기능으로 30 일 동안 제한없이 무료로 사용해 볼 수 있습니다.

관련 기사 :


최고의 사무 생산성 도구

Excel 용 Kutools는 대부분의 문제를 해결하고 생산성을 80 % 향상시킵니다.

  • 재사용: 빠르게 삽입 복잡한 공식, 차트 그리고 이전에 사용한 모든 것; 셀 암호화 암호로; 메일 링리스트 생성 이메일 보내기 ...
  • 슈퍼 포뮬러 바 (여러 줄의 텍스트와 수식을 쉽게 편집 할 수 있습니다.) 레이아웃 읽기 (많은 수의 셀을 쉽게 읽고 편집합니다.) 필터링 된 범위에 붙여 넣기...
  • 셀 / 행 / 열 병합 데이터 손실없이; 셀 내용 분할; 중복 행 / 열 결합... 중복 셀 방지; 범위 비교...
  • 중복 또는 고유 선택 행; 빈 행 선택 (모든 셀이 비어 있음); 슈퍼 찾기 및 퍼지 찾기 많은 통합 문서에서; 무작위 선택 ...
  • 정확한 사본 수식 참조를 변경하지 않고 여러 셀; 참조 자동 생성 여러 시트에; 글 머리 기호 삽입, 확인란 등 ...
  • 텍스트 추출, 텍스트 추가, 위치 별 제거, 공간 제거; 페이징 부분합을 만들고 인쇄합니다. 셀 내용과 주석 간 변환...
  • 슈퍼 필터 (다른 시트에 필터 구성표 저장 및 적용) 고급 정렬 월 / 주 / 일, 빈도 등 특수 필터 굵은 기울임 꼴로 ...
  • 통합 문서와 워크 시트 결합; 키 열을 기반으로 테이블 병합; 데이터를 여러 시트로 분할; xls, xlsx 및 PDF 일괄 변환...
  • 300 개 이상의 강력한 기능. Office / Excel 2007-2019 및 365를 지원합니다. 모든 언어를 지원합니다. 기업 또는 조직에 쉽게 배포 할 수 있습니다. 전체 기능 30 일 무료 평가판. 60 일 환불 보장.
kte 탭 201905

Office Tab은 Office에 탭 인터페이스를 제공하여 작업을 훨씬 쉽게 만듭니다.

  • Word, Excel, PowerPoint에서 탭 편집 및 읽기 사용, Publisher, Access, Visio 및 Project.
  • 새 창이 아닌 동일한 창의 새 탭에서 여러 문서를 열고 만듭니다.
  • 생산성을 50 % 향상시키고 매일 수백 번의 마우스 클릭을 줄입니다!
officetab 하단
Say something here...
symbols left.
You are guest
or post as a guest, but your post won't be published automatically.
Loading comment... The comment will be refreshed after 00:00.
  • To post as a guest, your comment is unpublished.
    Dan · 19 days ago
    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.
  • To post as a guest, your comment is unpublished.
    Robin · 10 months ago
    This is working for me, but the file extension is not changing. Any tips?
    • To post as a guest, your comment is unpublished.
      Pascal · 7 months ago
      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.
    • To post as a guest, your comment is unpublished.
      stevehurm · 10 months ago
      Same for me -- all files remain .csv.
      • To post as a guest, your comment is unpublished.
        Sunny · 7 months ago
        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.
  • To post as a guest, your comment is unpublished.
    Dixon · 1 years ago
    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?
  • To post as a guest, your comment is unpublished.
    Jason · 1 years ago
    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
    • To post as a guest, your comment is unpublished.
      Sunny · 1 years ago
      Thanks for your reminder, I have updated it, thanks again.
  • To post as a guest, your comment is unpublished.
    aaqil Rahman · 1 years ago
    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
  • To post as a guest, your comment is unpublished.
    viper · 1 years ago
    it changes my date column format from dd-mm-yyyy to dd/mm/yyyy, please can anyone help with how to prevent this script from changing column formats.
    Thanks a lot.
    • To post as a guest, your comment is unpublished.
      Sunny · 1 years ago
      Hi, viper, after conversion, you can format them back, select the dates and right click to choose Format Cells from context menu, in the Format Celld dialog, under Number tab, click Custom in the Category list, then type mm-dd-yyyy into the textbox in right section. Or if you have Kutools for Excel, applying the Apply Date Formatting to change the date format as you need.
  • To post as a guest, your comment is unpublished.
    Sam · 2 years ago
    One small issue with this code is that some accuracy (number of decimals) can be lost when opening a csv and saving it as xlsx.
    The way to prevent this is to select all cells right after opening, set the number of decimal places to the desired amount (15 for me personally), and *then* saving as xlsx

    Otherwise, the xlsx has less detail (less accuracy in terms of decimals) than the original csv, which can lead to problems in some applications
  • To post as a guest, your comment is unpublished.
    Rose · 2 years ago
    this macro does not show my csv file
  • To post as a guest, your comment is unpublished.
    stb · 2 years ago
    Cool bit of code. Very useful. If I'm not mistaken the code for .xlsx looks the same as the .xls code.

    This line:
    ActiveWorkbook.SaveAs Replace(xSPath & xCSVFile, ".csv", ".xls", vbTextCompare), xlWorkbookDefault

    I assume it should be: ".csv" , ".xlsx", vbTextCompare etc.
    • To post as a guest, your comment is unpublished.
      iBrezel · 2 years ago
      I've changed the code so, described above; now the script works as expected: it generates xlsx files
      • To post as a guest, your comment is unpublished.
        thy · 2 years ago
        no you haven't. it still says xls in both versions.
  • To post as a guest, your comment is unpublished.
    koliarpramod935@gmail.com · 2 years ago
    Great Script after searching all other script available in google. Can anybody help how to modify this script by specifying a folder location in local drive instead of allowing it to open the dialog box as i am actually automating the system. Thanks in advance
  • To post as a guest, your comment is unpublished.
    Pramod Koliar · 2 years ago
    Hi, great script which worked for me after trying all other script available in google. I have added few more lines which performs the text to columns operation which i want. Can anybody help me how to modify the script by specifying the folder location in local drive instead of opening the dialog box as i am actually automating the system
    . Thanks in advance
    • To post as a guest, your comment is unpublished.
      equiposlagares@gmail.com · 2 years ago
      Hi
      Could you share the script that performs the text to columns??
      Best Regards
  • To post as a guest, your comment is unpublished.
    HC · 2 years ago
    Hello,

    a great article - thank you! Almost works for me.

    Here's the problem: I have a pipe-delimited csv file. I have changed the default windows delimiter (via control panel/regional settings) to "|". So, when I open the csv file with Excel, it opens, directly reads and parses the fields to columns correctly. All I have to do is to save as xls or xlsx, done. When I look at your code, that should be what the code does: It opens the csv files in a folder, saves them as xls or xlsx, and loops over that.

    Here is the problem: When I open those Excel files, the pipe delimiters are still there, nothing is parsed to the columns. This was the behavior as before my change to the pipe delimited default setting in the Windows settings. So it seems like Excel doesn't use those Windows settings. I verified this by replacing the pipe delimiters with comma delimiters in a copy of the file - of the two files, the pipe-delimited remained unparsed, the comma delimited got converted just fine.

    Any idea where that Excel-inbuilt comma delimitation can be found or changed, or whether there is a way in the code to do that? I would prefer NOT to have to do a search and replace, then save...

    Thanks, HC
    • To post as a guest, your comment is unpublished.
      Sunny · 2 years ago
      If you want to split the data into column based on the pipe delimiter in Excel, just use Text to Columns function to split data by / after coverting the csv files to xls.
      • To post as a guest, your comment is unpublished.
        Sat · 10 months ago
        Doesn't really make the code useful for excel files.
  • To post as a guest, your comment is unpublished.
    Fred Maye · 2 years ago
    WHen I gave the folder name, the program said, "No files match your search." But there are 2,609 .csv files in the folder
    • To post as a guest, your comment is unpublished.
      Sunny · 2 years ago
      The code not support the separated comma csv file, are your files in this case?
  • To post as a guest, your comment is unpublished.
    ptee · 3 years ago
    I used the file multiple csv to multiple xls but get wrong xls de csv files have ; seperated info but become together in cells. How can this been solved?
    • To post as a guest, your comment is unpublished.
      Sunny · 2 years ago
      The code cannot support the separated comma csv file.
  • To post as a guest, your comment is unpublished.
    Dragos · 3 years ago
    Hi,

    Your script is great but it doesn't convert the csv separated by semicolons. Can you please post a solution for those?

    Thank you
    • To post as a guest, your comment is unpublished.
      strauss113 · 2 years ago
      i might be late i just got the issue where i needed to convert the semicolons CSV files and i added this to the code and it worked hope this will help someone

      Change 'Workbooks.Open Filename:=xSPath & xCSVFile' By this 'Workbooks.Open Filename:=xSPath & xCSVFile, Delimiter:=";", Local:=True'
    • To post as a guest, your comment is unpublished.
      Sunny · 3 years ago
      Sorry,here I do not have any solution, maybe you can place your question to our forum, someone else may help you. https://www.extendoffice.com/forum.html
  • To post as a guest, your comment is unpublished.
    Sathish · 3 years ago
    Thankyou so much for your excellent script for CSV to XLS. Its much more useful to my work
  • To post as a guest, your comment is unpublished.
    mathaio · 3 years ago
    "Tip: If you want to convert CSV files to XLXS files, you just need to change .xls to .xlsx in the macro ActiveWorkbook.SaveAs Replace(xSPath & xCSVFile, ".csv", ".xls", vbTextCompare)."

    I tried this, and Excel could not open the resulting files. I got the following message: "Excel cannot open the file 'filename.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."

    However, the script was successful for converting to .xls.
    • To post as a guest, your comment is unpublished.
      Sunny · 3 years ago
      I did not find that problem before, thank you for your correct comment. I have corrected the tip.
  • To post as a guest, your comment is unpublished.
    Karen · 3 years ago
    I want to do the opposite - convert XLS to CSV. does this script work?
    Sub CSVtoXLS()
    'UpdatebyExtendoffice20170814
    Dim xFd As FileDialog
    Dim xSPath As String
    Dim xXLSFile 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 + "\"
    xXLSFile = Dir(xSPath & "*.xls")
    Do While xXLSFile <> ""
    Application.StatusBar = "Converting: " & xXLSFile
    Workbooks.Open Filename:=xSPath & xXLSFile
    ActiveWorkbook.SaveAs Replace(xSPath & xXLSFile, ".xls", ".csv", vbTextCompare), xlNormal
    ActiveWorkbook.Close
    Windows(xWsheet).Activate
    xXLSFile = Dir
    Loop
    Application.StatusBar = False
    Application.DisplayAlerts = True
    End Sub
    • To post as a guest, your comment is unpublished.
      brad · 1 years ago
      Sub ConvertCSVToXlsx()

      Dim myfile As String
      Dim oldfname As String, newfname As String
      Dim workfile
      Dim folderName As String

      Application.DisplayAlerts = False
      Application.ScreenUpdating = False

      ' Capture name of current file
      myfile = ActiveWorkbook.Name

      ' Set folder name to work through
      folderName = "D:\tmp\"

      ' Loop through all CSV filres in folder
      workfile = Dir(folderName & "*.CSV")
      Do While workfile <> ""
      ' Open CSV file
      Workbooks.Open Filename:=folderName & workfile
      ' Capture name of old CSV file
      oldfname = ActiveWorkbook.FullName
      ' Convert to XLSX
      newfname = folderName & Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4) & ".xlsx"
      ActiveWorkbook.SaveAs Filename:=newfname, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=True
      ActiveWorkbook.Close
      ' Delete old CSV file
      Kill oldfname
      Windows(myfile).Activate
      workfile = Dir()
      Loop

      Application.DisplayAlerts = True
      Application.ScreenUpdating = True

      End Sub