-1

I've mixed code and get good results considering that I wish to create csv file without header and for first 12 columns of file.

Also, I've found way to send message about successful creation. My main problem now, is the fact that I can't push code to ask me if file exists, and to create it just after confirmation.

The best solution will be if I may on easier way do next:

  • create csv for range defined in code
  • confirm if I wish to overwrite existing file
  • open file in notepad

Below is code and obviously I need help

Private Sub CommandButton1_Click()
Dim fs As Object, a As Object, i As Integer, s As String, t As String, l As String, mn As String, PathCSV As String, NameCSV As String

    PathCSV = "D:\BOM\"
    NameCSV = "MMA - " & Format(Date, "mmmm yyyy") & ".csv"
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set a = fs.CreateTextFile("D:\BOM\MMA - " & Format(Date, "mmmm yyyy") & ".csv", True)

    For r = 5 To Range("A65536").End(xlUp).Row 'start in row 5  due row 1-4 is header
        s = ""
        c = 1
        While c < 13
            s = s & Cells(r, c) & ","
            c = c + 1
        Wend
        a.writeline s 'write line
    Next r
    MsgBox "CSV file successfully save to " & PathCSV & NameCSV
End Sub
QHarr
  • 83,427
  • 12
  • 54
  • 101
Radomir
  • 9
  • 5
  • 2
    Not sure I understand the question but if you're trying to turn off (or on) the prompts for overwriting a file, you might want to check https://stackoverflow.com/questions/14634453/how-to-use-workbook-saveas-with-automatic-overwrite . If, however, you actually want to create your own prompt to confirm the overwrite, you can use MsgBox with vbYesNoCancel - see David Zemens' example https://stackoverflow.com/a/16839561/8676647 – ifo20 Aug 11 '18 at 21:32
  • I've tried several example as well as one suggested by you, but I didn't implement in code in good way. Probably I should check if file exists before creation but I am not so familiar with this part of VBA. Thanks – Radomir Aug 12 '18 at 06:17

1 Answers1

0

try use the snippet

if fs.FileExists(pathcsv & namecsv) then
    overwrite = msgbox("overwrite?", vbyesno)
    if overwrite = vbno then exit sub
end if
PaichengWu
  • 2,649
  • 1
  • 14
  • 28