If worksheet name then - excel

I need to open a Workbook, it always has only one worksheet. Now I need to check the worksheets name and set a printrange. If not that worksheet name, check netxt worksheet name and so on.
This is what i got:
$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $true
$Workbook = $Excel.workbooks.open($RG)
If ($WorkSheets = $WorkBook.WorkSheets | where {$_.name -eq "Test1"}
$Data = $workbook.Worksheets.Item(1)
$Data.PageSetup.PrintArea = "C1:S60"
If ($WorkSheets = $WorkBook.WorkSheets | where {$_.name -eq "Test2"}
$Data = $workbook.Worksheets.Item(1)
$Data.PageSetup.PrintArea = "C1:S80"
What am I doing wrong?

Got it done:
If ($WorkBook.WorkSheets | where {$_.name -eq "Test1"})
{$Data = $workbook.Worksheets.Item(1)
$Data.PageSetup.PrintArea = "A1:Q50"}
If ($WorkBook.WorkSheets | where {$_.name -eq "Test2"})
{$Data = $workbook.Worksheets.Item(1)
$Data.PageSetup.PrintArea = "A1:R50"}

Related

How do I replace all occurrences of string in Excel documents in a folder using Powershell

I was able to find here the code for Word Document files, how could I use /adjust the same set of code to run Excel files
Thanks
$objWord = New-Object -comobject Word.Application
$objWord.Visible = $false
$list = Get-ChildItem "C:\Users\john\foldername\*.*" -Include *.doc*
foreach($item in $list){
$objDoc = $objWord.Documents.Open($item.FullName,$true)
$objSelection = $objWord.Selection
$wdFindContinue = 1
$FindText = "1911"
$MatchCase = $False
$MatchWholeWord = $true
$MatchWildcards = $False
$MatchSoundsLike = $False
$MatchAllWordForms = $False
$Forward = $True
$Wrap = $wdFindContinue
$Format = $False
$wdReplaceNone = 0
$ReplaceWith = "456"
$wdFindContinue = 1
$ReplaceAll = 2
$a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord, `
$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,`
$Wrap,$Format,$ReplaceWith,$ReplaceAll)
$objDoc.Save()
$objDoc.Close()
}
$objWord.Quit()
Based on this answer, you could do something like this:
$folderPath = "C:\Users\john\foldername\*"
$fileType = "*.xls*"
$excel = New-Object -ComObject Excel.Application
$textToReplace = #{
# "TextToFind" = "TextToReplaceWith"
"This1" = "That1"
"This2" = "That2"
"This3" = "That3"
}
Function findAndReplace($wsheet, $FindText, $ReplaceWith) {
#simple Replace to execute on all columns of a Worksheet object
$wsheet.Columns.Replace($FindText, $ReplaceWith) > $null
}
Function findAndReplaceMulti($wsheet, $lookupTable) {
#apply multiple Replace on the same Worksheet object
$lookupTable.GetEnumerator() | ForEach-Object {
findAndReplace $wsheet $_.Key $_.Value
}
}
Function findAndReplaceWholeWb($wbook, $lookupTable) {
#apply multiple Replace in all Worksheets
$wbook.Worksheets | ForEach-Object {
findAndReplaceMulti $_ $lookupTable
}
}
Get-ChildItem -Path $folderPath -Recurse -Filter $fileType | ForEach-Object {
$excel.Visible = $False
Write-Host "Processing `"$($_.Name)`"..."
$wbook = $excel.Workbooks.Open($_.FullName)
findAndReplaceWholeWb $wbook $textToReplace
$wbook.Close($True)
}
$excel.Quit()
$excel = $null
[gc]::collect()
[gc]::WaitForPendingFinalizers()

How to return a cell range (e.g. A10:C20) from a named range in Excel using PowerShell

I need to know how to return a cell range (e.g. A10:C20) from a named range called "Items" in Excel using PowerShell. I would like to delete entries in the second column of "Items" (B10:B20). I tried using .RefersToLocal method to return the range but it doesn't return anything. I'm new to PowerShell. Thank you for your help.
$Path = "C:\file.xls"
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $false
$Workbook = $Excel.Workbooks.Open($Path)
$page = 'Main'
$ws = $Workbook.worksheets | where-object {$_.Name -eq $page}
$ws.Range("Items").RefersToLocal
you can use range directly and then use the column attribute of the range elements (2 for B column) to clear and save it, like this:
$Path = "i:\named.xls"
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $false
$Workbook = $Excel.Workbooks.Open($Path)
$page = 'Main'
$ws = $Workbook.worksheets | where-object {$_.Name -eq $page}
$namedarea = $ws.Range("items")
$namedarea | ?{$_.column -eq 2} | %{$_.clear()}
$excel.Save()

need some help getting powershell do delete cell content and inserting a formula

Here is the script as it sits. $of is set to the name of the file that gets downloaded with wget. I am getting exception from HRESULT: 0x0800A03EC which has something to do with the range portion and it seeing a 0 based range, but I am giving it 2 : # of rows.
How can I get PowerShell to clear the range and then insert the formula?
#open the downloaded worksheet
$Excel = New-Object -Com Excel.Application
$Workbook = $Excel.Workbooks.Open($of)
$page = 'Project Summary'
$ws = $Workbook.Worksheets | Where-Object {$_.Name -eq $page}
# Set variables for the worksheet cells, and for navigation
$cells = $ws.Cells
$row = 1
$col = 5
# Add the header to the worksheet
$headers = "Region"
$headers | foreach {
$cells.Item($row, $col) = $_
}
# Add the formula to each occupied row
$rows = $worksheet.UsedRange.Rows.Count
$ws.Range("E2:E" + $rows).Clear()
$ws.Range("E2:E" + $rows).Formula = "=SUM(E2:E5)"
$Excel.Visible = $true
$Excel.DisplayAlerts = $false
$Excel.ActiveWorkbook.SaveAs('W:\test.xlsx')
I also tried
$rows | foreach {
$ws.Cells("E" + $rows).Clear()
$ws.Cells("E" + $rows).Formula = "=SUM(E2:E5)"
}
That gives me a Value does not fall within the expected range error.
How can I get this to clear each cell in the range E2:E<lastRow> and then insert a formula?
I have gone back to the following after finding a way to escape the entire formula using #' ... '#; there was clearly an error in my escape sequence earlier, but the following is not performing exactly as expected either.
$ws.Range("E2:E$rows").Clear();
$ws.Range("E2:E$rows").Formula = $Formula1
This now populates the formula, but it comes in as text and not as a formula; I have to solve for this.
#open the downloaded worksheet
$Excel = New-Object -Com Excel.Application
$Workbook = $Excel.Workbooks.Open($of)
$page = 'Project Summary'
$ws = $Workbook.Worksheets | Where-Object {$_.Name -eq $page}
# Set variables for the worksheet cells, and for navigation
$cells = $ws.Cells
$row = 1
$col = 5
# Add the header to the worksheet
$headers = "Region"
#open the downloaded worksheet
$excel = New-Object -Com Excel.Application
$Workbook = $Excel.Workbooks.Open($of)
$page = 'Project Summary'
$ws = $Workbook.worksheets | where-object {$_.Name -eq $page}
$Formula1 = #"
=SUM(E2:E5)
"#
$cells=$ws.Cells
$row=1
$col=5
$range = $ws.UsedRange
$rows = $range.Rows.Count
$ws.Range("E2:E$rows").Clear();
$ws.Range("E2:E$rows").Formula = $Formula1
# Add the header to the worksheet
$headers = "Region"
$headers | foreach {
$cells.item($row, $col) = $_
}
$excel.visible = $true
$excel.DisplayAlerts = $False
$excel.ActiveWorkbook.SaveAs('W:\Test.xlsx')
$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
Remove-Item $of
This is the outcome. Escaping may or may not have been the original issue, but the help here guided me to a better way to deal with it if it was the issue. I still never solved why the loop was giving the value error, but this works so I won't have to tackle that yet; that is the next script which this post will also help me with.

Creating a powershell script to convert and excel worksheet to pdf

I have done some searching and have gotten close but, still don't have a completely working script. Does anyone know what I'm doing wrong and what I need to change or add for this to work correctly.
Here is the code:
$path = "D:\Geoff's Files"
$dir = "D:\Geoff's Files\*.xls
$xlFixedFormat = Microsft.Office.Interop.Excel.xlFixedFormatType" -as [type]
$latest = Get-ChildItem -Path $dir | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latest.name
$ExcelFile = "$latest"
$excel = New-Object -ComObject Excel.Application
$excel.visible = $true
$Workbook = $excel.workbooks.open($ExcelFile,2,$True)
$Worksheets = $Workbook.worksheets
$Worksheet = $Workbook.worksheets.Item(1)
$Worksheet.ExportAsFixedFormat($xlFixedFormat::XlTypePDF, $path)
$workbook.Close()
$excel.Quit()
it runs but, throws an error in Excel that says: "Document not saved. The document may be open, or an error may have been encountered when saving."
$path only points to a directory - this needs to be a full save path (including file name and extension) if you're going to pass it as an argument (see MSDN article on this method)
You can try and amend the existing filename and use that:
$saveFileName = $ExcelFile.Substring(0, $ExcelFile.LastIndexOf('.')) + .pdf"
Tried putting in the suggestion but, still says document not saved. Any idea what I'm doing wrong?
$path = "D:\Geoff's Files"
$dir = "D:\Geoff's Files\*.xls
$xlFixedFormat = Microsft.Office.Interop.Excel.xlFixedFormatType" -as [type]
$latest = Get-ChildItem -Path $dir | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latest.name
$ExcelFile = "$latest"
$excel = New-Object -ComObject Excel.Application
$excel.visible = $true
$Workbook = $excel.workbooks.open($ExcelFile,2,$True)
$Worksheets = $Workbook.worksheets
$Worksheet = $Workbook.worksheets.Item(1)
$saveFileName = "ExcelFile.Substring(0, $ExcelFile.LastIndexOf('.')) + .pdf"
$Worksheet.ExportAsFixedFormat($xlFixedFormat::XlTypePDF, $saveFileName)
$workbook.Close()
$excel.Quit()
You need to use full path when referencing file and the use of double quotes in the saveFileName needs correcting. See the working code below:
$path = "D:\Geoff's Files"
$dir = "D:\Geoff's Files\*.xls
$xlFixedFormat = Microsft.Office.Interop.Excel.xlFixedFormatType" -as [type]
$latest = Get-ChildItem -Path $dir | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latest.name
$ExcelFile = "$latest"
$excel = New-Object -ComObject Excel.Application
$excel.visible = $true
### needed to add path ### $Workbook = $excel.workbooks.open($ExcelFile,2,$True)
$Workbook = $excel.workbooks.open($path + "\" + $ExcelFile,2,$True)
$Worksheets = $Workbook.worksheets
$Worksheet = $Workbook.worksheets.Item(1)
### wrong use of quotes & needed to add path ### $saveFileName = "ExcelFile.Substring(0, $ExcelFile.LastIndexOf('.')) + .pdf"
$saveFileName = $ExcelFile.Substring(0, $ExcelFile.LastIndexOf('.')) + ".pdf"
$Worksheet.ExportAsFixedFormat($xlFixedFormat::XlTypePDF, $path + "\" + $saveFileName)
$workbook.Close()
$excel.Quit()

Excel (.xls file) - 4 sheets not possible?

need your help again!
This Script doesn't work. It works for the first 3 Sheets, but doesn't work for the last one. If I switch the itemnumber (eg. 3->4 and 4->3) the new 3 works and the new 4 does not. Is this some sort of bug? Or am I missing some commandlet to increase the "maximum sheet number"?
$Path = "C:\test.xls"
#Excelvar:
$Row = [int] 2
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $true
$Excel.DisplayAlerts = $false
#Sheets:
$ADUsers = "Active Directory Users"
$Groups = "Create Groups"
$UsertoGroup = "User to groups"
$DNS = "DNS"
#$Worksheet = $Workbook.Sheets.Add()
$checkxls = test-path -pathtype Any $Path
if ($checkxls -eq $false) {
$wb = $Excel.Workbooks.Add()
$ws1 = $wb.Worksheets.Item(1)
$ws1.Name = $ADUsers
$ws1.activate()
$ws2 = $wb.Worksheets.Item(2)
$ws2.Name = $Groups
$ws2.activate()
$ws3 = $wb.Worksheets.Item(3)
$ws3.Name = $UserToGroup
$ws3.activate()
$ws4 = $wb.Worksheets.Item(4)
$ws4.Name = $DNS
$ws4.activate()
$wb.SaveAs($Path)
$wb.Close()
$Excel.Quit()
Errorcode:
"Invalid Index. (Exception by HRESULT: 0x8002000B (DISP_E_BADINDEX))"
Thx for help in advance.
extra information:
using powershell 3.0
using excel 2010
I think it's because you're refering to a different workbook
this line
$wb = $Excel.Workbooks.Add()
implies you're working with a new workbook.
try adding
$wb.Worksheets.Add()
after the workbook is created, and see if that works.
$Path = "C:\test.xls"
#Excelvar:
$Row = [int] 2
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $true
$Excel.DisplayAlerts = $false
#Sheets:
$ADUsers = "Active Directory Users"
$Groups = "Create Groups"
$UsertoGroup = "User to groups"
$DNS = "DNS"
#$Worksheet = $Workbook.Sheets.Add()
$checkxls = test-path -pathtype Any $Path
if ($checkxls -eq $false) {
$wb = $Excel.Workbooks.Add()
$wb.Worksheets.add()
$ws1 = $wb.Worksheets.Item(1)
$ws1.Name = $ADUsers
$ws1.activate()
$ws2 = $wb.Worksheets.Item(2)
$ws2.Name = $Groups
$ws2.activate()
$ws3 = $wb.Worksheets.Item(3)
$ws3.Name = $UserToGroup
$ws3.activate()
$ws4 = $wb.Worksheets.Item(4)
$ws4.Name = $DNS
$ws4.activate()
$wb.SaveAs($Path)
$wb.Close()
$Excel.Quit()
Tried adding Sheet4 on excel and it is code is reading Sheet4 just fine
#Declare the file path and sheet name
$file = "C:\Documents\Folder\ExcelFile.xlsx"
$sheetName = "Sheet1"
#Create an instance of Excel.Application and Open Excel file
$objExcel = New-Object -ComObject Excel.Application
$workbook = $objExcel.Workbooks.Open($file)
$sheetCount = $workbook.Worksheets.Count
$sheet = $workbook.Worksheets.Item($sheetName)
$sheet4 = $workbook.Worksheets.Item("Sheet4")
Write-Host $sheetCount #sheet count is 4
$objExcel.Visible=$false
#Count max row
$rowMax = ($sheet.UsedRange.Rows).count
#Declare the starting positions
$rowName,$colName = 1,1
$rowAge,$colAge = 1,2
$rowCity,$colCity = 1,3
#loop to get values and store it
for ($i=1; $i -le $rowMax-1; $i++)
{
$name = $sheet.Cells.Item($rowName+$i,$colName).text
$age = $sheet.Cells.Item($rowAge+$i,$colAge).text
$city = $sheet.Cells.Item($rowCity+$i,$colCity).text
Write-Host ("My Name is: "+$name)
Write-Host ("My Age is: "+$age)
Write-Host ("I live in: "+$city)
}
#used $rowMax from Sheet1, you can declare a separate for Sheet4
for ($i=1; $i -le $rowMax-1; $i++)
{
$name = $sheet4.Cells.Item($rowName+$i,$colName).text
$age = $sheet4.Cells.Item($rowAge+$i,$colAge).text
$city = $sheet4.Cells.Item($rowCity+$i,$colCity).text
Write-Host ("My Name is: "+$name)
Write-Host ("My Age is: "+$age)
Write-Host ("I live in: "+$city)
}
#close excel file
$objExcel.quit()
Pardon my example, just a noob script :)

Resources