Submitted By: Kent Finkle

Sets the print area in a Microsoft Excel spreadsheet.

PowerShell
Edit|Remove
$comments = @'
Script name: Set-PrintArea.ps1
Created on: Friday, July 06, 2007
Author: Kent Finkle
Purpose: How can I use Windows Powershell to
Set the Print Area in an Excel Spreadsheet?
'@
#-----------------------------------------------------
function Release-Ref ($ref) {
([System.Runtime.InteropServices.Marshal]::ReleaseComObject(
[System.__ComObject]$ref) -gt 0)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers() 
}
#-----------------------------------------------------
$xl = new-object -comobject excel.application
$xl.Visible = $True
$wb = $xl.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)
 
$2d = new-object 'object[,]' 10,10

for ($i = 0; $i -le 9; $i++) {
    for ($j = 0; $j -le 9; $j++) {
        $2d[$i,$j] = $i * $j + 1
    }
}
 
$r = $ws.Range("a1:j10")

$r.Value() = $2d
 
$ws.PageSetup.PrintArea = "B2:D4"
 
$a = Release-Ref($r)
$a = Release-Ref($ws)
$a = Release-Ref($wb)
$a = Release-Ref($xl)