vba - Ending a For-Loop that goes through worksheets in Excel -
i appreciate if can following. following code copies range ms excel , paste ms powerpoint. additionally, there loop goes through worksheets of workbook , applies same copy , paste formula. however, i'm struggling how "close" loop when reaches last worksheet. @ end of code, run-time error '91': object variable or block variable not set highlights sh(activesheet.index + 1).select
when select debug.
sub createdeck() dim wsheet_count integer dim integer dim rng excel.range dim pptapp powerpoint.application dim myppt powerpoint.presentation dim myslide powerpoint.slide dim myshaperange powerpoint.shape dim sh worksheet 'set wsheet_count equal number of worksheet in active workbook wsheet_count = activeworkbook.worksheets.count 'around world: loop = 1 wsheet_count 'copy range excel set rng = thisworkbook.activesheet.range("a1:a2") 'creat instance powerpoint on error resume next 'check if powerpoint open set pptapp = getobject(class:="powerpoint.application") 'clear error between errors err.clear 'open powerpoint if not open if pptapp nothing set pptapp = createobject(class:="powerpoint.application") 'handle if powerpoint cannot found if err.number = 429 msgbox ("powerpoint couldn't found, aborting") exit sub end if on error goto 0 'make powerpoint visible , active pptapp.visible = true pptapp.activate 'create new powerpoint if pptapp nothing set pptapp = new powerpoint.application end if 'make new presentation if pptapp.presentations.count = 0 pptapp.presentations.add end if 'add slide presentation pptapp.activepresentation.slides.add pptapp.activepresentation.slides.count + 1, pplayoutblank pptapp.activewindow.view.gotoslide pptapp.activepresentation.slides.count set myslide = pptapp.activepresentation.slides(pptapp.activepresentation.slides.count) 'copy excel range rng.copy 'paste powerpoint , position myslide.shapes.pastespecial datatype:=pppasteenhancedmetafile set myshaperange = myslide.shapes(myslide.shapes.count) 'set position myshaperange.left = 0 myshaperange.top = 0 myshaperange.height = 450 'clear clipboard application.cutcopymode = false 'next worksheet tab sh(activesheet.index + 1).select next end sub
your script great job of looping through worksheets
, there built-in collection
designed situation.
thisworkbook.worksheets
contains worksheets
in thisworkbook
-- can loop through this:
option explicit public sub loopthroughallworksheets() dim wks worksheet each wks in thisworkbook.worksheets msgbox "on sheet: " & wks.index next wks end sub
this means can tweak for...next
loop work this:
for each sh in thisworkbook.worksheets 'do stuff, like: 'set rng = sh.range("a1:a2") 'etc. next sh
leveraging worksheets
collection helps avoid using .select
, activesheet
, can cause users lot of pain:
Comments
Post a Comment