I needed a way to open an Excel file and run one of the macro’s inside the file to do some calculations and import some data then save the file as a new file, with the name of the previous month and its year added to it, to differentiate it from the original file.
Make sure macros are enabled within Excel, otherwise they’ll be disabled when opening the Excel file which will result in the script not working.
When working with Excel and PowerShell, when you’re living outside of the US, make sure you set the CurrentCulture to EN-US, otherwise you’ll get several Excel errors.
I’ll first save the CurrentCulture setting in a variable, so I can change it back after the script finishes. So, in the beginning of the script I’ll have these lines:
$CurrentCulture = [System.Threading.Thread]::CurrentThread.CurrentCulture.Name
[System.Threading.Thread]::CurrentThread.CurrentCulture = "en-US"
And after the script finishes, I’ll set it back like this:
[System.Threading.Thread]::CurrentThread.CurrentCulture = $CurrentCulture
To get the name of the month and the year, use the following two lines. I like to have the month name start with a capital letter, thus I add the third line of code:
$dateTextMonth = Get-Date -Date (Get-Date).AddMonths(-1) -format MMMM
$dateTextYear = Get-Date -Date (Get-Date).AddMonths(-1) -format yyyy
$dateTextMonthString = $dateTextMonth.Substring(0,1).toUpper() + $dateTextMonth.Substring(1).ToLower()
Now we can open Excel, open the file and run the macro. I’ll set the Excel save format to an Excel file with macros enabled.
Add-Type -AssemblyName Microsoft.Office.Interop.Excel
$xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlOpenXMLWorkbookMacroEnabled
$app = New-Object -comobject Excel.Application
$app.Visible = $True
$app.DisplayAlerts = $False
$wb = $App.Workbooks.Open("$folderName\$fileName.xlsm")
$App.Run("MacroNameToRun")
$app.ActiveWorkbook.SaveAs("$folderName\$fileName $dateTextMonthString $dateTextYear.xlsm", $xlFixedFormat)
$app.Quit()
And now it’ll open Excel, open the macro enabled workbook, run the macro, save the workbook with a new name and close Excel.
Sometimes the script would be to quick, thus I needed to add a start-sleep for 1 second, to make sure the Excel file is opened in Excel before I run the macro.
The complete script can be downloaded here.