简体   繁体   中英

VBA Excel export the file as .csv with keeping data in the proper columns

I want to have the.csv file saved with the columns as they look in my mother's workbook.

I used the following code:

Application.DisplayAlerts = False

     For Each Wksht In ActiveWorkbook.Worksheets


      myPath = ThisWorkbook.Path & "\"

       ActiveWorkbook.Sheets(Wksht.Index).Copy
       ActiveWorkbook.SaveAs Filename:=myPath & "Address list - NEW", FileFormat:=xlCSV, 
       CreateBackup:=False
       ActiveWorkbook.Close

       Next Wksht

       Application.DisplayAlerts = True

but instead of clear data separated by columns with their title headers, I am getting everything messy in one column.

在此处输入图像描述

What am I missing here?

Try the next way of opening, please (@VBasic2008, too):

Workbooks.OpenText Filename:=myPath & "Address list - NEW", Origin _
        :=437, StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote _
        , Tab:=False, Comma:=True

If it does not work, please test the solution secommended by VBasic2008:

Workbooks.Open Filename:=myPath & "Address list - NEW", Format:=2

If the above solutions do not work (not tested), or even if they work but need an alternative, try the next way to split the resulted (one column) opening:

Private Sub testTestTextToColumns()
  Dim i As Long, sh As Worksheet, rng As Range
  Set sh = ActiveSheet
  
    Set rng = sh.Range("A:A")
    rng.TextToColumns Destination:=sh.Range("A:C"), Comma:=True, FieldInfo:=Array(Array(1, 2), Array(1, 2), Array(1, 2))
End Sub

Note: The second code should process the default opening result. What you obtain now when try opening the csv...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM