excel - Save 3 Columns of a Worksheet as CSV (with VBA) -
i have problem visual basic, generate csv 3 columns, b m r, have code here not generating 3 columns whole worksheet, me?
sub gravatxt() dim pasta workbook dim abaplan worksheet dim b range dim m range dim r range dim name string name = range("r13").value set b = activecell.entirecolumn("b") set m = activecell.entirecolumn("m") set r = activecell.entirecolumn("r") set abaplan = thisworkbook.worksheets("orcamento") set pasta = application.workbooks.add abaplan.copy before:=pasta.worksheets(pasta.worksheets.count) application.displayalerts = false pasta.saveas filename:="c:\users\alcir.scarmin\desktop\" & name & ".csv", fileformat:=xlcsv application.displayalerts = true pasta.close savechanges:=false end sub
edit
made small modification (of @pehs answer) able run correctly, way left takes line "20" how can make offset? tried in several ways , did not work. (i'm brazilian, i'm using google translator, brazilian people not themselves) thank you.
sub gravatxt() dim abaplan worksheet set abaplan = thisworkbook.worksheets("orcamento") dim name string name = abaplan.range("r13").value dim pasta workbook set pasta = application.workbooks.add abaplan.range("b20,m20,r20").copy pasta.worksheets(1).range("a1") pasta.worksheets(1).name = abaplan.name application.displayalerts = false pasta.saveas filename:="c:\users\alcir.scarmin\desktop\" & name & ".csv", fileformat:=xlcsv application.displayalerts = true pasta.close savechanges:=false end sub
this because copied whole worksheet abaplan.copy
need copy columns abaplan.range("b:b,m:m,r:r").copy
.
option explicit sub gravatxt() dim abaplan worksheet set abaplan = thisworkbook.worksheets("orcamento") 'source workbook dim name string name = abaplan.range("r13").value 'always refer ranges specific worksheet dim pasta workbook set pasta = application.workbooks.add 'copy columns b, m , r new workbook first worksheet abaplan.range("b:b,m:m,r:r").copy pasta.worksheets(1).range("a1") pasta.worksheets(1).name = abaplan.name 'rename first worksheet same name abaplan application.displayalerts = false pasta.saveas filename:="c:\users\alcir.scarmin\desktop\" & name & ".csv", fileformat:=xlcsv application.displayalerts = true pasta.close savechanges:=false end sub
note
recommend use
filename:=environ("userprofile") & "\desktop\" & name & ".csv"
instead of hard coded path.
also aware using name
r13 without check if contains characters valid filename result in errors.
Comments
Post a Comment