How to Insert Excel Formula using PowerShell? - excel

The formula =LEFT(AB4,FIND(" ",AB5)-1 works perfectly in Excel, but seems to be causing errors in PowerShell where I get this error:
Exception from HRESULT: 0x800A03EC
At C:\Scripts\Excel_NUID2.ps1:21 char:1
+ $worksheet.range("AH5:AH$rows").formula = "=LEFT(AB4,FIND(" ",AB5)-1"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
My PowerShell Script Code;
#Open Up the Workbook#
$excel = new-object -comobject Excel.Application
$excel.visible = $false
$workbook =
$excel.workbooks.open("c:\Users\Jack\documents\NUID_Status_Report.xlsx")
$worksheet = $workbook.Worksheets.Item(1)
$rows = $worksheet.range("A1").currentregion.rows.count
### Set up a filter ###
$headerRange = $worksheet.Range("a4","aj4")
$headerRange.AutoFilter() | Out-Null
#### Trims Password Expiration Date Name ###
$worksheet.range("AH4").formula = "Shortened Expiration Date"
[void]$worksheet.Cells.Item(1,1).select()
$excel.visible = $true
#### Trims Password Expiration Date Formula ###
$worksheet.range("AH5:AH$rows").formula = "=LEFT(AB4,FIND(" ",AB5)-1"
[void]$worksheet.Cells.Item(1,1).select()
$excel.visible = $true

Quotes within a quoted string need to be doubled-up.
$worksheet.range("AH5:AH$rows").formula = "=LEFT(AB4,FIND("" "",AB5)-1)"
'you can also get rid of the inside quotes with the CHAR function
$worksheet.range("AH5:AH$rows").formula = "=LEFT(AB4, FIND(CHAR(32), AB5)-1)"
ASCII character 32 is a space. I've also added a bracket to make a legal formula.

Related

Change Worksheet Name (Excel) via Powershell

I have an challenge that I need to change on a daily basis in a XLSX document the existing sheet name to a new sheet name and than save it
My script looks like this:
$xlspath = "C:\Users\roger\Test - Test\Daily_Files\Testfile.xlsx"
$xldoc = new-object -comobject Excel.application
$xldoc.DisplayAlerts = $false
$xldoc.Visible =$false
$workbook = $xldoc.Workbooks.Open($xlspath)
$worksheet = $workbook.worksheets.item(1)
$worksheet.name = "Headcount"
$workbook.Save = ($xlspath)
$workbook.Close()
$xldoc.Quit()
I always get this error - even so the file gets save and the name has changed:
C:\CommonUserData\Roger\Test\Test.ps1:8 char:1
+ $workbook.Save = "C:\Users\roger\Test - Test\Daily_Files\ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException ```
Does someone have an idea how to solve this or make this a very simple script?
You don't even need the .Save() or .SaveAs() methods for this. Just close the workbook with parameter $true:
$xlspath = "C:\Users\roger\Test - Test\Daily_Files\Testfile.xlsx"
$xldoc = New-Object -ComObject Excel.application
$xldoc.DisplayAlerts = $false
$xldoc.Visible =$false
$workbook = $xldoc.Workbooks.Open($xlspath)
$worksheet = $workbook.worksheets.item(1)
$worksheet.Name = "Headcount"
$workbook.Close($true) # save the updated workbook
$xldoc.Quit()
# Important: remove references to the used COM objects when finished so they don't keep lingering in memory
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($worksheet)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($xldoc)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

Powershell , Cannot save as that name. Document was opened as read-only

How to avoid remove read-only , I need to normal excel without read-only.
I have below code:
$excelfile="C:\Users\Administrator\Pictures\unprotect_org - Copy\unprotect - Copy (2).xlsx"
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
$wb = $excel.Workbooks.Open($excelfile,$true,123)
$wb.SaveAs($excelfile,[Type]::Missing,$password)
$excel.Quit()
I got below error:
Cannot save as that name. Document was opened as read-only.
At line:1 char:1
+ $wb.SaveAs($excelfile,[Type]::Missing,$password)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
2nd things , why microsoft execel open in task manager, How can I close this exe.
Please help me to resolve this error.
Two things you'll want to change - opening in read-write mode, and ensuring Quit() is called regardless of terminating errors.
To avoid opening the workbook in read-only mode, change the value of the 3rd parameter argument passed to Open():
$wb = $excel.Workbooks.Open($excelfile,$true,$false)
# ^
# This is the ReadOnly parameter
To ensure Quit() is always called, use a try/finally statement:
$excelfile="C:\Users\Administrator\Pictures\unprotect_org - Copy\unprotect - Copy (2).xlsx"
$excel = New-Object -ComObject Excel.Application
try {
$excel.Visible = $false
$excel.DisplayAlerts = $false
$wb = $excel.Workbooks.Open($excelfile,$true,123)
$wb.SaveAs($excelfile,[Type]::Missing,$password)
}
finally {
$excel.Quit()
}
If PowerShell reaches the first statement inside the try block, it guarantees that the finally block will execute before returning control from the block - even if the call to SaveAs() (or any other invocation) throws a terminating exception

Powershell excel(xlsx) how unprotect excel sheet and excel workbooks with know password

I have below code:
$excelfile="C:\Users\Administrator\Pictures\unprotect_org - Copy (2)\unprotect - Copy (2).xlsx"
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
$wb = $excel.Workbooks.Open($excelfile,$false,123)
$wb.Unprotect(123);
$wb.Settings.Password = "";
$wb.Save($excelfile);
$excel.Quit()
I have problem with, PS script is opening ui excel application instead of remove password as without open excel.
Getting below error:
Unable to get the Open property of the Workbooks class
At line:1 char:1
+ $wb = $excel.Workbooks.Open($excelfile,$false,123)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
Please help to unprotect excel sheets and workbook using powershell.
Ok, here you go:
To open an Excel workbook with a password, you need to specify that password as the fith parameter on the Workbooks.Open() method:
$password = '123'
$excelfile = "C:\Users\Administrator\Pictures\unprotect_org - Copy (2)\unprotect - Copy (2).xlsx"
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
$wb = $excel.Workbooks.Open($excelfile, $false, $false, [Type]::Missing, $password)
# remove the protection from this workbook
$wb.Unprotect($password)
# should not be needed, but does no harm
$wb.Password=$null
# close the workbook and save the changes
$wb.Close($true)
$excel.Quit()
# Important: remove the used COM objects from memory
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($wb)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

Error when trying to protect Excel file with PowerShell

I'm trying to execute a PowerShell script for password protecting an Excel file.
this is the script:
Set objExcel = CreateObject(“Excel.Application”)
objExcel.Visible = True
objExcel.DisplayAlerts = FALSE
Set objWorkbook = objExcel.Workbooks.Add
Set objWorksheet = objWorkbook.Worksheets(1)
objWorksheet.Cells(1, 1).Value = Now
objWorkbook.SaveAs “C:\Test.xlsx”,,”%reTG54w”
objExcel.Quit
I tried running it using "run as PowerShell" but it closes automatically, I've also tried using the PowerShell ISE, the result is the one below:
the text for it is this:
At C:\Users\gasgu\OneDrive\Desktop\pwoershell.ps1:14 char:39
+ objWorkbook.SaveAs “C:\Test.xlsxâ€,,â€%reTG54wâ€
+ ~
Missing expression after ',' in pipeline element.
At C:\Users\gasgu\OneDrive\Desktop\pwoershell.ps1:14 char:39
+ objWorkbook.SaveAs “C:\Test.xlsxâ€,,â€%reTG54wâ€
+ ~
Missing argument in parameter list.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : MissingExpression
I've found this script from this url: https://devblogs.microsoft.com/scripting/how-can-i-password-protect-an-excel-spreadsheet/
But if it worth mentioning, what I'm trying to do is to pick up an Excel file from my PC (.xlsx) and password protect it (creating a new copy) now, in this script what I don't understand is if it's picking the excel file from somewhere as I don't see a line that explicitly says this.
Edit: The script I was executing ended up not being PowerShell, per clarification of #BigBen (see comments and approved answer) the script is VBS. He provided with script in PowerShell that performs the needed result.
That is VBScript, not Powershell. Perhaps try this:
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$excel.DisplayAlerts = $false
$wb = $excel.Workbooks.Add()
$wb.Worksheets("Sheet1").Cells(1, 1).Value = Get-Date
$wb.SaveAs("C:\Test.xlsx",[Type]::Missing,"%reTG54w")
$excel.Quit()
Perhaps this:
$Files = Get-ChildItem C:\Users\xxxx\Downloads\test\*.xlsx -Recurse
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
ForEach($File in $Files){
try {
$Workbook = $Excel.Workbooks.Open($File)
$Workbook.SaveAs($File,[Type]::Missing,"1234") #password set to 1234
$Workbook.Close($false)
$Excel.Quit()
}
catch {
}
}
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)

Freeze the top row of a worksheet

PowerShell code creates Excel.
I am trying to freeze top row:
$excel = New-Object -Com Excel.Application
$excel.Visible = $True
$wb = $Excel.Workbooks.Add()
$ws = $wb.Worksheets.Add()
$ws.Activate()
$ws.Select()
$excel.Rows.Item("1:1").Select()
$excel.ActiveWindow.FreezePanes = $true
Instead of freezing top row, it freezes center of rows and center of columns, i.e.
UPDATE
Solution in the duplicate post does not work, i.e.
$excel.Rows("1:1").Select()
$excel.ActiveWindow.FreezePanes = $true
gives the following error:
Method invocation failed because [System.__ComObject] does not contain a method named 'Rows'.
At D:\Script\upgrades.ps1:231 char:5
+ $excel.Rows("1:1").Select()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Rows:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
To freeze the top row you need to select the second row:
$excel.Rows.Item("2:2").Select()
$excel.ActiveWindow.FreezePanes = $true
If you have multiple sheets and need to freeze the top row of each sheet:
$colSheets = ($Sheet1, $Sheet2, $Sheet3, $Sheet4, $Sheet5)
foreach ($page in $colSheets){
$page.Select()
$page.application.activewindow.splitcolumn = 0
$page.application.activewindow.splitrow = 1
$page.application.activewindow.freezepanes = $true
}
#After you are done, re-select first sheet (optional)
$Sheet1.Select()
$excel.Application.ActiveWindow.SplitRow = 1
$excel.Application.ActiveWindow.FreezePanes = $true

Resources