2014-11-14 40 views
0

我想使用宏將excel文件導出爲csv。如何使用宏將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 
+0

所需輸出的問題似乎並沒有滿足你的代碼。也許看看這個最近的線程可能會有所幫助。 http://stackoverflow.com/questions/26676354/macro-for-exporting-text-files-from-excel-file-with-multiple-worksheets/26676831#26676831 – barryleajo

+0

@barryleajo我嘗試第一個腳本,我得到一個錯誤,說..「超出範圍」,而第二個腳本,它總是重複保存步驟,當我檢查csv。沒有記錄 – User014019

+0

是 - 將示例想象爲可能需要修改以滿足數據和要求的模板。它是針對那個問題的要求寫的,不是你的。 – barryleajo

回答

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