Export range to csv file

YasserKhalil
PlatinumLounger
Posts: 4911
Joined: 31 Aug 2016, 09:02

Export range to csv file

Post by YasserKhalil »

Hello everyone
I have the following code that works fine and exports the range to csv file

Code: Select all

    Dim sFile As String, tmp As String, f As Integer, r As Long, c As Long
    sFile = ThisWorkbook.Path & "\Output_" & Format(Now, "dd-mm-yyyy_hh:mm") & ".csv"
    f = FreeFile
    Open sFile For Output Access Write As #f
    With ThisWorkbook.Worksheets("Data")
        For r = 1 To .Cells(Rows.Count, "E").End(xlUp).Row
            tmp = vbNullString
            For c = 5 To 6
                tmp = tmp & IIf(tmp = Empty, Empty, ",") & .Cells(r, c).Value
            Next c
            Print #f, tmp
        Next r
    End With
    Close #f
The weird in the code when using this line
sFile = ThisWorkbook.Path & "\Output_" & Format(Now, "dd-mm-yyyy_hh:mm") & ".csv"
The csv file is not valid and it seems the extension is not defined to windows while if I used the name directly like that "Output.csv", the code works fine. Any idea?

YasserKhalil
PlatinumLounger
Posts: 4911
Joined: 31 Aug 2016, 09:02

Re: Export range to csv file

Post by YasserKhalil »

I think the problem is with the format of Now as I put : in the format and this may caused the problem. When deleting the : , the code works fine

User avatar
HansV
Administrator
Posts: 78229
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Export range to csv file

Post by HansV »

Don't use : in a filename, it's not a valid character.
For example, use Format(Now, "dd-mm-yyyy_hh-mm")
Best wishes,
Hans

User avatar
SpeakEasy
4StarLounger
Posts: 535
Joined: 27 Jun 2021, 10:46

Re: Export range to csv file

Post by SpeakEasy »


YasserKhalil
PlatinumLounger
Posts: 4911
Joined: 31 Aug 2016, 09:02

Re: Export range to csv file

Post by YasserKhalil »

Thank you very much.