forked from dfinke/ImportExcel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd-ExcelName.ps1
More file actions
30 lines (30 loc) · 1.38 KB
/
Copy pathAdd-ExcelName.ps1
File metadata and controls
30 lines (30 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
function Add-ExcelName {
[CmdletBinding()]
param(
#The range of cells to assign as a name.
[Parameter(Mandatory=$true)]
[OfficeOpenXml.ExcelRange]$Range,
#The name to assign to the range. If the name exists it will be updated to the new range. If no name is specified, the first cell in the range will be used as the name.
[String]$RangeName
)
try {
$ws = $Range.Worksheet
if (-not $RangeName) {
$RangeName = $ws.Cells[$Range.Start.Address].Value
$Range = ($Range.Worksheet.cells[($range.start.row +1), $range.start.Column , $range.end.row, $range.end.column])
}
if ($RangeName -match '\W') {
Write-Warning -Message "Range name '$RangeName' contains illegal characters, they will be replaced with '_'."
$RangeName = $RangeName -replace '\W','_'
}
if ($ws.names[$RangeName]) {
Write-verbose -Message "Updating Named range '$RangeName' to $($Range.FullAddressAbsolute)."
$ws.Names[$RangeName].Address = $Range.FullAddressAbsolute
}
else {
Write-verbose -Message "Creating Named range '$RangeName' as $($Range.FullAddressAbsolute)."
$null = $ws.Names.Add($RangeName, $Range)
}
}
catch {Write-Warning -Message "Failed adding named range '$RangeName' to worksheet '$($ws.Name)': $_" }
}