簡體   English   中英

如何使用宏將Excel文件導出為csv?

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

我想使用宏將Excel文件導出為csv。

但是我的代碼僅導出每列的標題,而不導出在excel文件中輸入的整個記錄​​,並且標題顯示在第二行而不是第一行。

如何解決這個問題?

另外,如果在excel文件中輸入了新列和新記錄,該怎么辦。 如何在宏中確定這一點? 有可能的? 謝謝

巨集:

 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

需求輸出:

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

我已經解決了這個問題

 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