Excel VBA - Creating new sheets and pasting stuff in raise 1004 Error -
i have issue excel vba code below. 1004 error when block commented out active.
error result:
- the first sheet in array created, header row pasted in , formatted correctly
- second sheet created, no header row pasted
- error stops script @ point -> no further sheets created
i cant figure out problem is, can help?
dim ws1 worksheet: set ws1 = activeworkbook.sheets("agestock") dim newsheets(1 4) string newsheets(1) = "chem - also" newsheets(2) = "lbs - lbla" newsheets(3) = "lbs - lbfg" newsheets(4) = "chemicals" dim sheetname variant 'copy header row ws1 ws1.cells(1, 1).entirerow.copy 'create new worksheets each sheetname in newsheets sheets.add after:=worksheets(worksheets.count) activesheet.name = sheetname 'paste header row activesheet.cells(1, 1).select activesheet.paste ' autofit columns & zoom & scroll activewindow.zoom = 90 activesheet.columns("a:y").autofit activesheet.columns("b").columnwidth = 60 'description activesheet.columns("e").columnwidth = 12 'was activesheet.columns("f").columnwidth = 12 'now 'this section breaks 'format was, now, avgcost, value currency ' activesheet.columns("e").numberformat = "$#,##0.00" 'was ' activesheet.columns("f").numberformat = "$#,##0.00" 'now ' activesheet.columns("h").numberformat = "$#,##0.00" 'avgcost ' activesheet.columns("l").numberformat = "$#,##0.00" 'value next sheetname ws1.activate
this because excel's copying , pasting vba horrible. i'd suggest using following macro instead. note assign range, , copy directly destination (no messy selection takes place). makes things lot more reliable, because excel handles whole copy operation, not windows. think. makes things work me though.
public sub test() dim newsheets(1 4) string newsheets(1) = "chem - also" newsheets(2) = "lbs - lbla" newsheets(3) = "lbs - lbfg" newsheets(4) = "chemicals" dim sheetname variant dim ws1 excel.worksheet dim rngcopytarget excel.range set ws1 = thisworkbook.sheets(1) 'copy header row ws1 set rngcopytarget = ws1.cells(1, 1).entirerow 'create new worksheets each sheetname in newsheets sheets.add after:=worksheets(worksheets.count) activesheet.name = sheetname 'paste header row rngcopytarget.copy activesheet.range(rngcopytarget.address) ' autofit columns & zoom & scroll activewindow.zoom = 90 activesheet.columns("a:y").autofit activesheet.columns("b").columnwidth = 60 'description activesheet.columns("e").columnwidth = 12 'was activesheet.columns("f").columnwidth = 12 'now 'this section breaks 'format was, now, avgcost, value currency activesheet.columns("e").numberformat = "$#,##0.00" 'was activesheet.columns("f").numberformat = "$#,##0.00" 'now activesheet.columns("h").numberformat = "$#,##0.00" 'avgcost activesheet.columns("l").numberformat = "$#,##0.00" 'value next sheetname ws1.activate end sub
Comments
Post a Comment