简体   繁体   中英

How to use powershell to run personal macro with different paths

I am trying to create automatically a report out of an excel file. I already analyzed one specific file and the report is saved local.

Now I want to use this macro to run it on other files. Therefore I have to change the path in the powershell.

Now I want to run the macro automatically (let`s say at 1am) with powershell.

$excel = New-Object -comobject Excel.Application
$wbPersonalXLSB = $excel.workbooks.open("C:\Users\fami\AppData\Roaming\Microsoft\Excel\XLSTART\PERSONAL.XLSB")
$FilePath = "C:\Users\fami\Desktop\example.xls"
$workbook = $excel.Workbooks.Open($FilePath)
$excel.Visible = $false
$worksheet = $workbook.worksheets.item(1)
$excel.Run("PERSONAL.XLSB!run")
$wbPersonalXLSB.Close()
$workbook.save()
$workbook.close()
$excel.quit()

Only the $FilePath needs to be variable.

You just need to use a Parameter for the $FilePath variable instead of hard coding it. Like this:

param([string]$FilePath)

$excel = New-Object -comobject Excel.Application
$wbPersonalXLSB = $excel.workbooks.open("C:\Users\fami\AppData\Roaming\Microsoft\Excel\XLSTART\PERSONAL.XLSB")
$workbook = $excel.Workbooks.Open($FilePath)
$excel.Visible = $false
$worksheet = $workbook.worksheets.item(1)
$excel.Run("PERSONAL.XLSB!run")
$wbPersonalXLSB.Close()
$workbook.save()
$workbook.close()
$excel.quit()

Then you would schedule the script and specify the -FilePath paramater like so:

powershell.exe -file C:\folder\yourscript.ps1 -FilePath "C:\Users\fami\Desktop\example.xls"

EDIT : To read a list of files from a text file (with one file on each line) would be this.

param(
    [string]$FileList,
    [string]$PersonalXLSB="C:\Users\fami\AppData\Roaming\Microsoft\Excel\XLSTART\PERSONAL.XLSB",
    [string]$RunMacro="PERSONAL.XLSB!run"
)

$Files = Get-Content $FileList

foreach ($FilePath in $Files) {
    $excel = New-Object -comobject Excel.Application
    $wbPersonalXLSB = $excel.workbooks.open($PersonalXLSB)
    $workbook = $excel.Workbooks.Open($FilePath)
    $excel.Visible = $false
    $worksheet = $workbook.worksheets.item(1)
    $excel.Run($RunMacro)
    $wbPersonalXLSB.Close()
    $workbook.save()
    $workbook.close()
    $excel.quit()
}

I've also moved the PersonalXLSB and Macro to Params, as they have a value set this will be used as default if you don't specify anything else. It's most basic form is like this:

    powershell.exe -file C:\folder\yourscript.ps1 -FileList "C:\folder\name.text"

You can change the other params like this:

    powershell.exe -file C:\folder\yourscript.ps1 -FileList "C:\folder\name.text" -RunMacro="PERSONAL.XLSB!macroname"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM