Vbsript and excel delete all sheets except the last

I am trying to delete the entire worksheet in excel except the last one and save it and then move its location. I cannot get it to work, as it deletes all other worksheets, but the errors are error and out of range.

Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True objExcel.DisplayAlerts = False Set objWorkbook = objExcel.Workbooks.Open("C:\M-tek 10-31-12_Tony.xlsx") i = objWorkbook.Worksheets.Count Do while i = i i = i - 1 objWorkbook.Worksheets(i).Delete Loop 
+4
source share
1 answer

Your loop will be infinite, since your condition can never be false ( i will always be equal to i ). So you need to change your loop to get started with the worksheet of the latter, but skip to the first. You are almost there.

 count = objWorkbook.Worksheets.Count - 1 For i = count To 1 Step -1 objWorkbook.Worksheets{i}.Delete Next 

That should do it (actually it is, I just tested it).

+1
source

All Articles