2014-06-12 53 views
0

今天我遇到了一個嘗試逐行寫入csv文件的問題,其中一列格式化爲本地Excel日期。我的腳本可以正常工作,但不能正確導出日期,並且正在以串行字符串的形式導出。我只是希望導出的文件以「mm/dd/yyyy」格式寫入日期。有任何想法嗎?將本地excel日期導出爲文本字符串

Sub OUTPUT_COMMA_DELIMITED_RANGE() 

Dim outputPath As String 
Dim outputFileName As String 
Dim rSrc As Range 
Dim rSrcRow As Range 
Dim fso As FileSystemObject 
Dim fOut As TextStream 

On Error GoTo SomethingBadHappened 
Dim MyPathFull As String 



outputPath = "C:\workspace\Appendix_Working_Area\Script_Out\" 

    outputFileName = "Z225R" & Chr(95) & "Eddy_Fluctuating_Zone.csv" 
MyPathFull = outputPath & outputFileName 


    Set fso = CreateObject("scripting.filesystemobject") 
    Set fOut = fso.CreateTextFile(outputPath & outputFileName) 

    Dim EddyHghEleZoneRng As Range 

    Set EddyHghEleZoneRng = Worksheets("225R").Range(Cells(1, 9), Cells(1, 9).End(xlToRight).End(xlDown)) 
    Set rSrc = EddyHghEleZoneRng 

    For Each rSrcRow In rSrc.Rows 
     fOut.WriteLine Join(Application.WorksheetFunction.Transpose _ 
          (Application.WorksheetFunction.Transpose(rSrcRow)), ",") 
    Next rSrcRow 

    MsgBox "File " & outputPath & outputFileName & " created successfully" 

SomethingBadHappened: 
If Err.Number <> 0 Then MsgBox Err.Description 
On Error Resume Next 
fOut.Close 
If Err.Number <> 0 And Err.Number <> 91 Then MsgBox "Unable to close file (" & Err.Description & ")" 
End Sub 

我選擇了手動創建CSV文件,因爲ID不希望任何與使用內置到Excel的FileFormat:=xlCSV功能有關的不良角色。

爲了提供我正在處理的數據類型的示例,我創建了一個我想要的輸出csv文件的樣例。

網站,日期,Plane_Height,Area_2D,Area_3D,體積,錯誤 225R,11/3/1990,8kto25k,2212.834,2235.460,841.76655,88.513

謝謝,

dubbbdan

+0

在Windows上不能使用'/'在一個文件名。 – enderland

回答

2

看來您的數據包含在6列中。這裏有一個方法,使的.csv它保留日期格式:

Sub MakeCSVFile() 
    Dim N As Long, M As Long, i As Long, j As Long 
    Dim OutRec As String 
    N = Cells(Rows.Count, "A").End(xlUp).Row 
    M = 6 
    Close #1 
    Open "C:\TestFolder\x.csv" For Output As #1 
    For i = 1 To N 
     OutRec = Cells(i, 1).Text 
     For j = 2 To M 
      OutRec = OutRec & "," & Cells(i, j).Text 
     Next j 
     Print #1, OutRec 
    Next i 
    Close #1 
End Sub 
+0

假設這6列是正確的。我如何使這個腳本工作,如果我有一個數據範圍?我需要從每個工作表中導出多個csv。 – dubbbdan

+0

該代碼需要知道每個**有多少行相關聯。csv ** –

+0

這將出現在「N =」行中嗎? – dubbbdan

相關問題