Make Excel Defined Names within a worksheet to be global - powershell

I wrote Powershell script to copy a worksheet from a workbook A to another workbook B. The worksheet contains define names for ranges within that sheet. Originally, the defined names are global in workbook A, ie. can be referenced from any worksheets within workbook A.
But now, after copy to worksheet B, the defined names are limited to that worksheet only. How to I programmatically (via Powershell script preferably) make all those named range global i.e. can be referenced from all worksheets within workbook B.
Some codes for clarity.
#Script to update SOP from 5.1 to 5.2
$missing = [System.Type]::missing
#Open files
$excel = New-Object -Com Excel.Application
$excel.Visible = $False
$excel.DisplayAlerts = $False
$newTemplate = "C:\WorkbookA.xls"
$wbTemplate = $excel.Workbooks.Open($newTemplate)
$oldSop = "C:\WorkbookB.xls"
$wbOldSop = $excel.Workbooks.Open($oldSop)
#Delete 'DATA' worksheet from old file
$wsOldData = $wbOldSop.Worksheets.Item("DATA")
$wsOldData.Delete()
#Copy new 'DATA' worksheet to old file
$wbTemplate.Worksheets.Item("DATA").Copy($missing,$wbOldSop.Worksheets.Item("STATUS"))
#Save
$wbOldSop.Save()
$wbOldSop.Close()
#Quit Excel
$excel.Quit()

I have this problem when copying worksheets with named ranges on them from directly in excel itself. I had this problem just last week. I couldn't find out why, and I suspect PowerShell really doesn't have anything to do about it. My only recourse seemed to be to drop and recreate the named ranges on the secondary sheets.

Related

Powershell - Get Worksheets from several excel files and save them into one excel file -with original file name as worksheet name-

I have searched the following code in the net, that works, but keep the original name of the worksheets when adding them in new excel file. I would need to set the original file name as the worksheet names.
Do you think that's possible? how?
Thanks!!
$ExcelObject=New-Object -ComObject excel.application
$ExcelObject.visible=$true
$ExcelFiles=Get-ChildItem -Path "C:\Users\XX/XX"
$Workbook=$ExcelObject.Workbooks.add()
$Worksheet=$Workbook.Sheets.Item("Sheet1")
foreach($ExcelFile in $ExcelFiles){
$Everyexcel=$ExcelObject.Workbooks.Open($ExcelFile.FullName)
$Everysheet=$Everyexcel.sheets.item(1)
$Everysheet.Copy($Worksheet)
$Everyexcel.Close()
}
$Workbook.SaveAs("C:\Users\XX\XX\merge.xlsx")
$ExcelObject.Quit()
Setting names is easy, the worksheet has a .Name property that you can set, and when you copy it into your new workbook it is automatically the active sheet in that workbook, so we add one line in your loop:
foreach($ExcelFile in $ExcelFiles){
$Everyexcel=$ExcelObject.Workbooks.Open($ExcelFile.FullName)
$Everysheet=$Everyexcel.sheets.item(1)
$Everysheet.Copy($Worksheet)
$Everyexcel.Close()
$Workbook.ActiveSheet.Name = $ExcelFile.Name
}

How can I add content at the end of a Microsoft Word docx document using PowerShell?

I am using PowerShell to open and edit a docx file.
I was able to open an existing file and set the style, font and more...
My problem is with adding content. The content is added to the top of the file but I want to add it at the end of the document.
This is my working code:
$word = New-Object -ComObject Word.Application
$word.Visible = $false
$out_path = ".\file.docx"
$doc = $word.documents.open($out_path)
$selections = $word.Selection
$selections.Font.Name = "Arial"
$selections.Font.Size = 16
$selections.paragraphFormat.Alignment = 2
$selections.TypeText("Hello World!`v")
$doc.Close()
$word.Quit()
This is the how I tested it:
I created a new docx file.
At the first run it will add the text to an empty existing word file.
If you run it again it will add the text but at the beginning of the document.
You can verify this by changing the String in the TypeText function before the second run.
I did not find any information about how to add a content at the end of the document using PowerShell.
I will appreciate any help,
Thank you.

Import CSV File to a new Excel Worksheet within an existing Excel Workbook

I'm Trying to import 2 different CSV files into an excel workbook on 2 different worksheets.
I've figured out how to create an excel workbook and import one of the CSV files. But when creating a new worksheet, I can't seem to import the 2nd CSV file into the new worksheet the same way that I imported the first CSV file.
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $true
$Excel = $Excel.Workbooks.open(C:\Temp\CSVfile1.csv)
#Create new worksheet and import 2nd CSV file
$Excel.Worksheets.add()
$Excel.Sheets(1).Name = 'Errors'
$Excel2 = $Excel.Workbooks.open(C:\Temp\CSVfile2.csv)
The first CSV file import is successful. The 2nd worksheet is created, but the 2nd csv file is not imported.
Error message displayed is
You cannot call a method on a null-valued expression.
I highly recommend using the ImportExcel module for any Excel-related files, it makes them much easier to work with and only takes a couple seconds to get it working. Moreover it has the benefit of using reading and editing Excel files without needing Microsoft Excel to be installed.
See the following example to do what you're looking for using the ImportExcel module:
Import-Csv -Path 'C:\Temp\CSVfile1.csv' | Export-Excel -Path 'C:\Temp\ExportExcelTest.xlsx' -WorkSheetname 'Sheet1'
Import-Csv -Path 'C:\Temp\CSVfile2.csv' | Export-Excel -Path 'C:\Temp\ExportExcelTest.xlsx' -WorkSheetname 'Errors'
Additionally, ImportExcel also comes along with many formatting options which may be of use to you. I can't recommend it enough over using a ComObject to modify an Excel file.

Printing all Excel files in a folder using PowerShell

I have a PowerShell script that I wrote a few years ago and it worked great...until it didn't.
$shell = New-Object -com Shell.Application
$filepath = 'C:\Billing\Clients'
$shell.Namespace($filepath).Items() |
% { $_.InvokeVerb('Print') }
In the C:\Billing\Clients folder I copy ~100 Excel files. Each of these Excel files need to be printed, in the alphabetical order of the file name.
This was working great until this month. I guess an update to Excel changed things.
Now the script tries to open and print all of the Excel files at the same time. Previously it printed the files in serial.
This was awesome. Now it brings my system to it's knees and documents are printed in a random order.
Any ideas on how I can invoke the Print operation and wait for it to complete prior to calling the Print operation on the next file?
I have used this in the past to pull files into excel and print them. You will need to ensure your default print settings are set first or use $xl.ActivePrinter = "PRINTERNAME AS EXCEL SEES IT" to set it first.
#Open Excel
$xl = new-object -comobject excel.application
#don't show the window
$xl.visible = $false
#get all of your files
get-childitem "C:\SOME\Path" "*.xlsx" | foreach-object {
#open file
$wb = $xl.Workbooks.Open($_.FullName)
#print with defaults
$wb.PrintOut()
#close without saving any changes
$wb.Close($false)
}
#all done so close excel
$xl.Quit()

Count the excel rows using the folder path

I have one folder named customer , under that there are multiple folders based on each customer name and under each customer I have excel of sheets which contain information in row wise.
I would like to extract this file structure into excel containing file path and number of rows contained in each of the excel.
I could able to list file names using below procedure.
Press Win-E to open Windows Explorer and locate the folder for which you need a file list.
Hold the Shift key, right-click the folder and select Open Command Window Here. This only works with folders, not libraries.
Libraries point to a specific folder, so select the folder located
under the library icon. If the library points to a drive, right-click
the drive letter from the folder tree.
Type dir /b > dirlist.txt without quotes and press Enter. This creates a list containing file names only. To include file sizes and
dates, type dir > dirlist.txt instead. To also include files in
sub-directories, type dir /b /s > dirlist.txt to create a list of
files with the full directory structure name, such as
C:\folder\subdirectory\file.txt.
Open Microsoft Excel and press Ctrl-O to bring up the Open dialog window.
Navigate into the folder containing the files. Click the file type drop-down menu and select Text Files (.prn,.txt,*.cvs).
Double-click dirlist.txt to open it.
Click Finish in the Text Import Wizard window to use the default options and import the directory list into Excel.
Please help in counting the rows also.
Your question is ambigous. I removed unnecessary/wrong tags.
Excel files can have more than one sheet, so you have to iterate/recurse the files from given startfolder and also all sheets in the workbook. Output is a table with the asked properties. Should be easy to save as a csv.
$BaseFolder = "X:\Path\to\Customers"
$xlCellTypeLastCell = 11
$AllSheets = New-Object System.Collections.Generic.List[object]
$Excel = New-Object -com excel.application
$Excel.DisplayAlerts = "False"
$XLfiles = Get-ChildItem -Path $BaseFolder -Filter *.xls* -File -Recurse
ForEach ($XLfile in $XLfiles) {
$WorkBook = $Excel.workbooks.open($XLfile.FullName)
for ($i = 1; $i -le $WorkBook.sheets.count; $i++){
$Sheet = $WorkBook.Sheets.Item($i)
$LastRow = $Sheet.UsedRange.SpecialCells($xlCellTypeLastCell).Row
$Obj = [pscustomobject][ordered]#{
ExcelFPath= $XLfile.FullName
Customer = ($XLfile.Directory).Name
ExcelFile = $XLfile.Name
SheetNo = $i
RowCount = $LastRow
}
$AllSheets.add($obj)
}
$Excel.Workbooks.Close()
}
$AllSheets | Format-Table -auto
## $AllSheets | Out-Gridview