Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vba 如何使用宏将excel文件导出为csv?_Vba_Excel_Csv - Fatal编程技术网

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

Vba 如何使用宏将excel文件导出为csv?,vba,excel,csv,Vba,Excel,Csv,我想使用宏将excel文件导出为csv 但我的代码只导出每列的标题,而不是excel文件中输入的全部记录,标题显示在第二行,而不是第一行 如何解决这个问题 另外,如果excel文件中输入了新列和新记录,该怎么办。如何在宏中确定这一点?有可能吗?多谢各位 宏: Sub WriteCSVFile() Dim My_filenumber As Integer Dim logSTR As String My_filenumber = FreeFile logSTR = logSTR &a

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

所需的输出似乎与代码不匹配。也许可以看看最近的这条线索,这可能会有所帮助@barryleajo说:“我尝试了第一个脚本,但发现了一个错误。”。。当第二个脚本超出范围时,它总是在我检查csv时重复保存步骤。没有记录-将该示例视为一个可能的模板,您必须对其进行修改以满足您的数据和需求。我知道,但我对vb和宏是新手。你能帮我一下吗?编辑你的Q,显示你的源数据是如何构造的,哪些数据需要写入文本文件。