Thursday, 15 September 2011

Excel's dodgy csv output


For some reason excel doesn't export csv's too well.  The major issue being it doesn't force speech marks into the export document and seems to change the dates from YYYY-MM-DD to MM-DD-YYYY.  This isn't letting us submit an ULN report to the Learning Record Service.  The following code creates a CSV with speech marks AND a YYYY-MM-DD date from the area that you select

Sub csvExport()
    Dim fs As Object, a As Object, i As Integer, s As String, t As String, l As String, mn As String
    Set fs = CreateObject("Scripting.FileSystemObject")
   
    Dim filename As String
    filename = "LRB_" & Range("C2").Value & "_" & Format(Date, "DDMMYYYY") & "1230.CSV"

    filename = InputBox(Prompt:="Enter the file name to save to", _
          Title:="CSV file name", Default:=filename)
    Set a = fs.CreateTextFile(filename, True)
   
    For r = 1 To Selection.Rows.Count
        s = """"
        c = 1
        For c = 1 To Selection.Columns.Count
                Dim temp As String
                temp = Selection.Cells(r, c)
                'special character catcher specific to LRS
                temp = Replace(temp, "&", "and")
                temp = Replace(temp, "'", "")
                temp = Replace(temp, ":", "")
             
                If IsDate(temp) And x Like "####-##-##" Then
                    s = s & Format(temp, "YYYY-MM-DD")
                Else
                    s = s & temp
                End If
               
                If c = Selection.Columns.Count Then
                    s = s & """" 'end of row
                Else
                    s = s & """,""" 'mid row
                End If
        Next c
        a.writeline s 'write line
    Next r
    MsgBox ("complete, see your root folder")

End Sub



No comments:

Post a Comment