【问题标题】:How to export excel file as csv using macro?如何使用宏将excel文件导出为csv?
【发布时间】:2014-11-14 06:47:43
【问题描述】:

我想使用宏将 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

【问题讨论】:

  • 您想要的输出似乎与您的代码不匹配。也许看看这个最近的线程可能会有所帮助。 stackoverflow.com/questions/26676354/…
  • @barryleajo 我尝试了第一个脚本,我得到一个错误,说..“超出范围”,而第二个脚本,它总是重复保存步骤,当我检查 csv 时。没有记录
  • 是的 - 将示例视为一个可能的模板,您必须对其进行修改以满足您的数据和要求。它是为该问题中的要求而不是您的要求而编写的。
  • 我知道,但我是 vb 和宏的新手。你能帮我解决这个问题吗?
  • 编辑 Q 以显示源数据的结构以及需要将哪些数据写入文本文件。

标签: vba excel csv


【解决方案1】:

我已经解决了这个问题

 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

【讨论】:

    猜你喜欢
    • 2021-10-24
    • 2012-10-27
    • 1970-01-01
    • 2016-03-29
    • 2012-03-15
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    相关资源
    最近更新 更多