delete worksheet from .xlsm file - excel

I am trying to delete a named Worksheet from an .xlsm file.
I followed the example posted here but it is not working for me. When I open the .xlsm file to check whether the Worksheet has been deleted, it is still there.
Here is my code:
$file2 = 'c:\file.xlsm' # destination's fullpath
$xl = new-object -c excel.application
$xl.displayAlerts = $false # don't prompt the user
$wb2 = $xl.workbooks.open($file2) # open target
$sh2_wb2 = $wb2.sheets | where {$_.name -eq "myWorksheet"}
$sh2_wb2.delete() #Delete original sheet in template
$wb2.close($true) # close and save destination workbook
$xl.quit()
spps -n excel
What am I doing wrong?
Edit:
I changed my code to make the Excel Object visible when opening it. I then noticed that the delete call is being sent, but it is asking the user to confirm whether the delete should happen: Data may exist in the sheet(s) selected for deletion. To permanently delete the data, press Delete.
I then attempted to add a few more displayAlerts = $false in my code, but it is still giving me that prompt.
Here's my updated code, although it still does not work.
$file2 = 'c:\file.xlsm' # destination's fullpath
$xl = new-object -com excel.application -Property #{Visible = $true}
$xl.displayAlerts = $false # don't prompt the user
$wb2 = $xl.workbooks.open($file2) # open target
$wb2.displayAlerts = $false # don't prompt the user
$sh2_wb2 = $wb2.sheets | where {$_.name -eq "myWorksheet"}
$sh2_wb2.displayAlerts = $false # don't prompt the user
$sh2_wb2.delete() #Delete original sheet in template
$wb2.close($true) # close and save destination workbook
$xl.quit()
spps -n excel

Try this, its help for me :
$Excel = New-Object -ComObject Excel.Application
$workbook = $Excel.workbooks.add()
#working with sheets
$workbook.worksheets.item("Sheet1").Delete()

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()

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)) {}

Inserting text from text file into existing Excel worksheet with PowerShell

I'm trying to insert the contents of my text file into cell A1 on Sheet1 but all I get is the filename inserted instead of the contents of the text file.
$Path = 'C:\folder\Test.xlsx'
$Text='C:\folder\text.txt'
# Open the Excel document and pull in the 'Play' worksheet
$Excel = New-Object -Com Excel.Application
$Excel.Visible=$true #For troubleshooting purposes only.
$Workbook = $Excel.Workbooks.Open($Path)
$page = 'Sheet1'
$ws = $Workbook.worksheets | where-object {$_.Name -eq $page}
# Set variables for the worksheet cells, and for navigation
$cells=$ws.Cells
$row=1
$col=1
$cells.item($Row,$col)=$Text
$col++
# Close the workbook and exit Excel
$workbook.Close($true)
$excel.quit()
That is because you set $Text to just the path to the file. You have to actually read the contents of the file with a cmdlet like Get-Content.
For example:
$Text = Get-Content 'C:\folder\text.txt'
However, depending on the contents of that text file, you may want to do that differently or you could end up with a messy result.

Powershell - Excel Rename Worksheets base upon filename

I have multiple excel files that I am combining into one excel document with multiple sheets. I would like to rename these sheets based upon the current file being processed name. CODE:
$files = Get-ChildItem "C:\Stuff\" -exclude "Pauls*"
$DestFile = 'C:\Stuff\Pauls Weekly KPI.xlsx' # source's fullpath
foreach($file in $files)
{
$baseName = [System.IO.Path]::GetFileNameWithoutExtension($file.fullname)
Write-Host $baseName
$xl = new-object -c excel.application
$xl.displayAlerts = $false # don't prompt the user
$wb1 = $xl.workbooks.open($file, $null, $true) # open source, readonly
$wb2 = $xl.workbooks.open($DestFile) # open target
$sh1_wb2 = $wb2.sheets.item(1) # first sheet in destination workbook
$sheetToCopy = $wb1.sheets.item('Report') # source sheet to copy
$sheetToCopy.copy($sh1_wb2) # copy source sheet to destination workbook
$wb1.close($false) # close source workbook w/o saving
$wb2.close($true) # close and save destination workbook
}
$xl.quit()
spps -n excel
Example:
After the script has run the final notebook would contain multiple sheets named by their original files name
Solved it by renaming the sheet prior to copying:
$files = Get-ChildItem "C:\Stuff\" -exclude "Pauls*"
$DestFile = 'C:\Stuff\Pauls Weekly KPI.xlsx' # source's fullpath
$xl = new-object -c excel.application
$xl.displayAlerts = $false # don't prompt the user
foreach($file in $files){
$baseName = [System.IO.Path]::GetFileNameWithoutExtension($file.fullname)
Write-Host $baseName
$wb1 = $xl.workbooks.open($file, $null, $true) # open source, readonly
$wb2 = $xl.workbooks.open($DestFile) # open target
$sh1_wb2 = $wb2.sheets.item(1) # first sheet in destination workbook
$sheetToCopy = $wb1.sheets.item('Report') # source sheet to copy
$sheetToCopy.name = $baseName
$sheetToCopy.copy($sh1_wb2) # copy source sheet to destination workbook
$wb1.close($false) # close source workbook w/o saving
$wb2.close($true) # close and save destination workbook
}
$xl.quit()
spps -n excel

Resources