简体   繁体   English

如何使用宏将Excel文件导出为csv?

[英]How to export excel file as csv using macro?

I want to export the excel file as csv using macro. 我想使用宏将Excel文件导出为csv。

But my code export only the header of each column, not the whole records that inputted in excel file and the header display on the 2nd row instead on 1st row. 但是我的代码仅导出每列的标题,而不导出在excel文件中输入的整个记录​​,并且标题显示在第二行而不是第一行。

How to fix this? 如何解决这个问题?

In additional, what if there's a new column and new records inputted in excel file. 另外,如果在excel文件中输入了新列和新记录,该怎么办。 How to determine this in macro? 如何在宏中确定这一点? It is possible? 有可能的? Thank you 谢谢

Macro: 巨集:

 Sub WriteCSVFile()

 Dim My_filenumber As Integer
 Dim logSTR As String

 My_filenumber = FreeFile

 logSTR = logSTR & Cells(1, "A").Value & " , "
 logSTR = logSTR & Cells(1, "B").Value & Format(Now, "yyyyMMddhhmmss") & " , "
 logSTR = logSTR & Cells(1, "C").Value & Format(Now, "yyyyMMddhhmmss") & " , "
 logSTR = logSTR & Cells(1, "D").Value & " , "
 logSTR = logSTR & Cells(1, "E").Value & " , "
 logSTR = logSTR & Cells(1, "F").Value & " , "
 logSTR = logSTR & Cells(1, "G").Value & " , "
 logSTR = logSTR & Cells(1, "H").Value & " , "
 logSTR = logSTR & Cells(1, "I").Value & " , "
 logSTR = logSTR & Cells(1, "J").Value & " , "
 logSTR = logSTR & Cells(1, "K").Value & " , "
 logSTR = logSTR & Cells(1, "L").Value & " , "
 logSTR = logSTR & Cells(1, "M").Value

 Open "C:\Users\username\foldername\Sample.csv" For Append As #My_filenumber
    Print #My_filenumber, logSTR
 Close #My_filenumber

End Sub

Desire output: 需求输出:

 Header1, Header2,    Header3, Header4
 1234456, 10/10/2014, Marc,    24

I already solve the issue with this 我已经解决了这个问题

 Dim DirLoc As Variant

DirLoc = "pathname"

'~~> Check if it is a valid entry
If DirLoc <> False Then
    '~~> Check before hand if the file exists
    If Not Dir(DirLoc) <> "" Then
        '~~> If not then save it
        ActiveWorkbook.SaveAs Filename:=DirLoc
    Else
        '~~> Trap the error and ignore it
        On Error Resume Next
        If Err.Number = 1004 Then
            On Error GoTo 0
        Else '<~~ If user press Save
            ActiveWorkbook.SaveAs Filename:=DirLoc, _
            FileFormat:=xlCSV, _
            ConflictResolution:=xlLocalSessionChanges
        End If
    End If
End If

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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