Powershell Send Key Excel - excel

I would like to write a script in Powershell which does the following:
Opens Excel Workbook.
Click two times enter on the 2 appearing DialogBoxes.
Runs a macro, saves workbook and quits.
I have a problem with the 2nd step. In my script enter is sent to Powershell window and I see two lines added to the code.
Could anyone help me? Here is my code:
$p1 = "C:\"
$eo = new-object -comobject excel.application;
$eoc = dir $p1 -Include *.xlsm -Recurse
Foreach ($f1 in $eoc)
{
$wb = $eo.workbooks.open($f1.fullname)
while (!$eo.Ready){sleep 0.1}
$eo.Application.SendKeys('~')
while (!$eo.Ready){sleep 0.1}
$eo.Application.SendKeys('~');
$eo.Run("macro_name");
$eo.Application.CalculateFull;
while (!$eo.Ready){sleep 0.1};
$wb.save(); $wb.close()
}
$eo.quit()

You need something like this.
$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate('window name of your excel file') | Out-Null
This will focus your excel workbook and execute your send key commands.

Related

PowerShell opens excel while running script and crashes

I have made some code to run a Macro on 560 Excel files.
There is a small issue with the code, it seems it doesn't save excel file, and opens every excel file, cause excel to crash.
is there a way to have the macro be ran on these 560 files in the backround, and to automatically save once macro is ran, rather than saving it manually?
Thanks
Here is my Code:
# start excel
$excel = New-Object -comobject Excel.Application
# get files
$files = Get-ChildItem 'C:\Users\ME\Desktop\TEST'
# loop through all files in the directory
ForEach ($file in $files){
# open the file
$workbook = $excel.Workbooks.Open($file.FullName)
# make file visible
$excel.Visible = $true
# run macro
$app = $excel.Application
$app.run("PERSONAL.xlsb!Module6.MyMacro")
}
By setting $excel.Visible = $true, the code will become much slower because of all the screen updates involved.
Also, you do not save the workbook after running the code, and because you never quit Excel and remove the COM objects from memory, eventually it will crash because of running out of resources.
Try:
# start excel
$excel = New-Object -comobject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
# get files and loop through the list
# the usual extension for macro-enabled Excel files is `*.xlsm`.
# if your files have this extension, add -Filter '*.xlsm' to the
# Get-ChildItem command below.
Get-ChildItem -Path 'C:\Users\ME\Desktop\TEST' -File | ForEach-Object {
# open the file
$workbook = $excel.Workbooks.Open($_.FullName)
# run macro
$app = $excel.Application
$app.run("PERSONAL.xlsb!Module6.MyMacro")
$workbook.Close($true) # $true --> save changes
}
$excel.Quit()
# cleanup COM objects
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

Powershell to refresh Excel with OLAP Query. Credential issues

I'm rather new with PowerShell scripting so please be patient with me :)
I have multiple excel file with OLAP Query connections connecting to Power BI Datasets, following are the script;
$libraryPath = "C:\Repos\AUSD\3.0\Test"
$excel = new-object -comobject Excel.Application
$excel.Visible = $false
# Give delay to open
Start-Sleep -s 3
$allExcelfiles = Get-ChildItem $libraryPath -recurse -include “*.xls*”
foreach ($file in $allExcelfiles)
{
$workbookpath = $file.fullname
Write-Host "Updating " $workbookpath
# Open the Excel file
$excelworkbook = $excel.workbooks.Open($workbookpath)
$connections = $excelworkbook.Connections
# This will Refresh All the pivot tables data.
$excelworkbook.RefreshAll()
# The following script lines will Save the file.
$excelworkbook.Save()
$excelworkbook.Close()
Write-Host "Update Complete " $workbookpath
}
$excel.quit()
It is working fine if following options;
$excel.Visible is true
However this is going to be scheduled in the server and hopefully this could be done in the background, hence the $excel.Visible = $false
This causing the following error;
I suspect this is due to the Automatic sign in which happen when the Excel are open, due to its not being open, its failing the sign in process.
How do I bypass or rather set the credentials/permission right?

Print hidden excel sheet from multiple workbooks with Powershell

I have monthly task os printing some data for pure accounting.
this data are in some excel workbooks on a hidden sheet, as it is now I have to open the workbook, reveal the sheet, print it and hide it again.
I would like to this task to automated.
All the workbooks are in the same directory
I have a Powershell script that can print every thing i one directory, but i don't know how to target a specific sheet let alone a hidden sheet
Code to print from one directory:
$files = Get-ChildItem “Y:\Booking\Send*.*”
foreach ($file in $files){
start-process -FilePath $file.fullName -Verb Print
}
how would i do this ?
The below will allow you to print the hidden sheet of a single excel workbook that you could extend to print multiple in a loop.
This will use the default printer set in windows.
$FilePath = Get-ChildItem "Y:\Booking\November\*.xls"
$HiddenSheet = "Administration"
$xl = New-Object -ComObject Excel.Application
$xl.Visible = $False
foreach ($file in $FilePath){
$wb = $xl.Workbooks.Open($file)
$ws = $wb.WorkSheets.Item($HiddenSheet)
$ws.Visible = $True
$ws.PrintOut()
$wb.close($false)
}
$xl.quit()
To be able to print the hidden sheet it needs to be set to visible, the script handles this and then closes the workbook and does not keep the changes.
You must declare the name of the $hiddensheet so if the name is different on each workbook I would suggest making a CSV with filepath and name of the sheet so that these can be passed through and handled accordingly.

Open, save and close Excel

I have an issue opening a spreadsheet via PowerShell, renaming a worksheet, saving and closing Excel. The issue is when run the first time the $WorkBook variable is null. If I run it a second time the script works fine. Also if I add $ExcelDoc.Visible = $true the script works fine. Does anyone have an idea why the script fails on it first run in the form it is below?
$Path = "C:\ScriptRepository\CQC\DataToLoad\"
$FileName = (Get-ChildItem $Path).FullName
$FileName2 = (Get-ChildItem $Path).Name
Start-Sleep 2
$ExcelDoc = New-Object -ComObject Excel.Application
$WorkBook = $ExcelDoc.Workbooks.Open($FileName)
$WorkSheet = $WorkBook.Worksheets.Item(2)
$WorkSheet.Name = "CQCProviders"
$WorkBook.Save()
$WorkBook.Close()
$ExcelDoc.Quit()
While([System.Runtime.Interopservices.Marshal]::ReleaseComObject($ExcelDoc)) {}

Powershell Excel automatic Bloomberg add-in

I have a problem with automatic run of Excel with Bloomberg add-in included.
When I manually open Excel worksheet, data functions from Bloomberg add-in automatically run.
But when I open same sheet with Powershell and save, there aren't any loaded data
Code - Start Excel and open Workbook:
$xls = New-Object -ComObject Excel.Application
$xls_workbook = $xls.Workbooks.Open("Market_data.xlsx")
$xls_workbook.Activate()
I have tried to force recalculation by these methods:
$xls.Calculate()
$xls.CalculateFull()
$xls.CalculateFullRebuild()
$xls.Workbooks.Application.CalculateFullRebuild()
$xls_workbook.Worksheets(1).Calculate()
But nothing worked. Strange, because, as I have mentioned, manual opening of Excel sheet causes that data from Bloomberg are loaded automatically.
Do you have some experience with this Bloomberg add-in automation? I wanted to check also .xla macros that are included (BloombergUI.xla, BloombergHistory.xla) but they are protected by passwords.
Maybe, is there any option to force running of all Add-ins in Excel?
Or is there any call like $xls.Application.Run() that can run this add-in?
Thank you
Whole code:
$xls = New-Object -ComObject Excel.Application
$xls_workbook = $xls.Workbooks.Open("MarketData.xlsx")
$xls_workbook.Activate()
#calculation
$xls.Calculate()
#$xls_workbook.Aplication.Run("RefreshAllStaticData") - THIS RETURNS ERROR, THAT MACRO IS NOT AVAILABLE OR MACROS ARE DISABLED
#my current option of waiting
$internal_timeout = new-timespan -Seconds $timeout
$sw = [diagnostics.stopwatch]::StartNew()
while ($sw.elapsed -lt $internal_timeout){
}
#maybe next option, how to wait until job finished
#$job = Start-Job -ScriptBlock {
#docalculation
#}
#Wait-Job $job -Timeout $timeout | out-null
$date = Get-Date -Format M_dd_yyyy
$file_to_save = "MarketData_$date.xlsx"
$xls_workbook.SaveAs($file_to_save)
$xls_workbook.Close();
$xls.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xls)
This code worked for me:
$xls = New-Object -ComObject Excel.Application
$xls.Workbooks.Open("C:\blp\API\Office Tools\BloombergUI.xla")
Write-Debug "$file_path$file_name$file_ext"
$xls_workbook = $xls.Workbooks.Open("$file_path$file_name$file_ext")
$xls_workbook.Activate()
$xls_workbook.Application.Run("RefreshAllWorkbooks")
$xls_workbook.Application.Run("RefreshAllStaticData")
$xls.CalculateFull()
Start-Sleep -s $timeout
$date = Get-Date -Format M_dd_yyyy
$file_to_upload = "$file_path$file_name$date$file_ext"
Write-Debug $file_to_upload
$xls_sheet = $xls_workbook.Sheets.Item(1)
$bl_value = $xls_sheet.Cells.Item(2,9).Text
Write-Host $bl_value
$xls_workbook.SaveAs($file_to_upload)
$xls_workbook.Close()
the bloomberg addin is not loaded at all when you use "New-Object -ComObject Excel.Application" to open excel. you can double check by alt+F11 in vba environment

Resources