Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding sheets to end of workbook in Excel (normal method not working?)

Tags:

This is the VBA code im using to try add a new sheet to the last place in the workbook

mainWB.Sheets.Add(After:=Sheets(Sheets.Count)).Name = new_sheet_name

I saw this in a similar question on this site. Its not working.

I do this in a loop and each sheet gets added to the second position in the sheets. There are 2 sheets that are permanently there (info and summary) and I then precede to add 5 more called "test" 1 through 5. I always end up with the sheets in this order:

Info, sheet5, sheet4, sheet3, sheet2, sheet1, Summary

But what I want/was expecting was:

Info, Summary, sheet1, sheet2, sheet3, sheet4, sheet5

(the loop does produce them in the expected order so the problem isn't there.)

If I swap the summary and info sheets before I start then they are in the opposite places when I'm done.

What am I doing wrong?

like image 909
Jacxel Avatar asked Jul 12 '12 16:07

Jacxel


People also ask

Is it possible to insert a sheet at the end of worksheet?

To quickly insert a new worksheet at the end of the existing worksheets, click the Insert Worksheet tab at the bottom of the screen. To insert a new worksheet in front of an existing worksheet, select that worksheet and then, on the Home tab, in the Cells group, click Insert, and then click Insert Sheet.

Why won't Excel let me insert a sheet?

Can't insert a new worksheet or delete an existing sheet? The option to add new sheet is greyed out? If the workbook structure is protected with a password, you're unable to add, delete, move, copy, rename, hide or unhide any sheets.

How would you move a worksheet to the end of a workbook?

Shift to the worksheet you want to copy to end of workbook, right click the sheet tab, and then click Move or Copy from the context menu. See screenshot: 2. In the Move or Copy dialog box, select (move to end) in the Before sheet box, and check the Create a copy box, then click the OK button.


3 Answers

Try this

mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name 
like image 130
Siddharth Rout Avatar answered Sep 27 '22 01:09

Siddharth Rout


mainWB.Sheets.Add(After:=Sheets(Sheets.Count)).Name = new_sheet_name 

should probably be

mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name 
like image 32
Tim Williams Avatar answered Sep 23 '22 01:09

Tim Williams


A common mistake is

mainWB.Sheets.Add(After:=Sheets.Count)

which leads to Error 1004. Although it is not clear at all from the official documentation, it turns out that the 'After' parameter cannot be an integer, it must be a reference to a sheet in the same workbook.

like image 21
MathKid Avatar answered Sep 25 '22 01:09

MathKid