file to saveas CSV format iin excel vba -
i have used following code saving active worksheet file not found in folder.
code reference:
sub save_csv() application.screenupdating = false application.displayalerts = false savename = "indented_bom" savepath = dir("c:\users\350153\desktop\automation (structures)") range("a1:d150").select range(selection, selection.end(xldown)).select range(selection, selection.end(xltoleft)).select selection.copy workbooks.add activesheet.range("a2") .pastespecial xlpastevalues .pastespecial xlpasteformats end activesheet.columns("a:d").autofit activeworkbook.saveas filename:=savepath & savename & ".csv" _ , fileformat:=xlcsvwindows, createbackup:=false activeworkbook.save activewindow.close application.screenupdating = true application.displayalerts = true msgbox "task finished", vbinformation, "finished"
end sub
you can without copy/paste, because worksheet
object has saveas
method, there no need do:
- create new workbook via
workbooks.add
- copy range of cells current workbook
- paste copied selection in new workbook (1)
- save new workbook (1)
instead, should:
- invoke
saveas
method on worksheet - remove rows (1-4) don't copy in previous code
it this, modified ensure file not exist. if file exists, msgbox
alerts , procedure exit without saving.
sub saveas_csv() dim savename$, savepath$, csvfullname$ application.screenupdating = false application.displayalerts = false savename = range("b2") savepath = range("b3") if right(savepath,1) <> application.pathseparator savepath = savepath & application.pathseparator csvfullname = savepath & savename & ".csv" if dir(csvfullname) <> "" 'file exists, alert user , exit procedure msgbox csvfullname & " exists! file not saved csv.", vbinformation goto earlyexit end if activesheet.saveas filename:=csvfullname _ , fileformat:=xlcsvwindows, createbackup:=false rows("1:4").entirerow.delete columns("a:d").autofit activewindow.close earlyexit: application.screenupdating = true application.displayalerts = true end sub
Comments
Post a Comment