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

时间:2014-11-14 06:47:44

标签: excel vba excel-vba csv

我想使用宏将excel文件导出为csv。

但是我的代码只导出每列的标题,而不是导出excel文件中的整个记录​​,而是在第2行而不是第1行显示标题。

如何解决这个问题?

另外,如果在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

1 个答案:

答案 0 :(得分:0)

我已经用这个

解决了这个问题
 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