I've been at this for quite a while,
I want to create a new worksheet by copying another. This places the new sheet before the sheet being copied. I then want to move it to the very end of all of the sheets.
The aim is to have worksheets called > summary1 > summary2 > summary3 .. etc in that order
Here is what I have (excuse brevity)
$ex = New-Object -ComObject Excel.Application
$ex.Visible = $true
$wb = $ex.Workbooks.Add()
for ($i = 1; $i -le 3; $i++)
{
$wb.Worksheets.Item(2).Copy($wb.Worksheets.Item(2))
$newSheet = $wb.Worksheets.Item(2)
$newSheet.Activate()
$name = "Summary$i"
$newSheet.Name = $name
$wb.Worksheets.Item($name).Move($wb.Worksheets.Item($i + 1))
}
It works for the first sheet, it renames the sheet then moves it to the end but after that everytime it reaches the .Move method it doesn't do anything except .Activate() the original "Summary" sheet.
I have no idea how to explain this behaviour.. Thankyou kindly in advance.
Edit: Changed $wb.Worksheets.Item("Summary").Move to $wb.Worksheets.Item($name).Move
Edit:
Here is the solution:
for ($i = 1; $i -le 3; $i++)
{
$wb.Worksheets.Item(2).Copy($wb.Worksheets.Item(2))
$newSheet = $wb.Worksheets.Item(2)
$newSheet.Activate()
$name = "Summary$i"
$newSheet.Name = $name
$lastSheet = $wb.WorkSheets.Item($wb.WorkSheets.Count)
$newSheet.Move([System.Reflection.Missing]::Value, $lastSheet)
}
On the Edit menu, click Sheet > Move or Copy Sheet. On the To book menu, click the workbook that you want to copy the sheet to. Tip: To create a new workbook that contains the moved sheet, click new book. In the Before sheet box, click the sheet that you want to insert the copied sheet before, or click move to end.
To locate the last cell that contains data or formatting, click anywhere in the worksheet, and then press CTRL+END.
In order to move one sheet to the right, hold down Ctrl, then press the PgDn key. To keep moving to the right, press the PgDn key again. In order to move back or one sheet to the left, hold down Ctrl, then press the PgUp key. To keep moving to the left, press the PgUp key again.
Click the sheet that you want to move to the other workbook. On the Edit menu, point to Sheet, and then click Move or Copy Sheet. In the To book box, select the workbook that you want to move the sheet to. Tip: To create a new workbook that contains the moved sheet, click (new book).
Marked as Community because it is from the question above.
Here is the solution:
for ($i = 1; $i -le 3; $i++)
{
$wb.Worksheets.Item(2).Copy($wb.Worksheets.Item(2))
$newSheet = $wb.Worksheets.Item(2)
$newSheet.Activate()
$name = "Summary$i"
$newSheet.Name = $name
$lastSheet = $wb.WorkSheets.Item($wb.WorkSheets.Count)
$newSheet.Move([System.Reflection.Missing]::Value, $lastSheet)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With