Cade W.
Cade W.

Reputation: 389

PowerShell - Excel - Select first worksheet in workbook

I have a script that loops through a workbook and copies all tabs to a new workbook. For some reason, though, the first tab is always being skipped.

for ($i=1; $i -lt $myworkbook.Worksheets.Count; $i++) {
... other code
$SheetToCopy = $source.Worksheets.Items($i)
$sheetToCopy.Copy($target)
}

Can anyone shed some light on what is going on here?

Additional Information:

The workbooks will never have the same named tabs, for this reason i'm using index rather than name.

Upvotes: 1

Views: 5902

Answers (1)

bamblack
bamblack

Reputation: 3779

From the code you posted it looks like it may be skipping the last sheet and not the first. It should be

(int i = 1; i <= worksheets.Count; i++) // roughly translated from C#

When you have the < sign there (instead of <=) and because you're using a non-zero based index, when it hits the last sheet i will be equal to worksheets.Count, therefore skipping it since you require it to be less than worksheets.Count

Upvotes: 2

Related Questions