简体   繁体   中英

Powershell run Excel macro with dynamic amount of parameters

I'm trying to automate some different Excel files with a start macro, where the additionals parameters are stored in a job CSV file atm.

The problem is how to build the run command for Excel where you run the macro, with parameters like this, where "Start" is the name of the macro and in this example 3 additional parameters.

$excel.Run("Start","param1","param2","param3")

I have tried building the command and parameters as a string like I would if it was a normal cmd-let , and then invoke-expression, but the run command just read it as one string.

So how do I build the Run command with a dynamic number of parameters, without building some kind of switch that handles lets say 1-5 different parameters. that all calls $excel.run command with different amount of parameters, that's just a bit ugly and not very dynamic.

Basically you are looking for a way to splat a method. That is only useful for cmdlets and functions, not methods. However PowerShell supports something called Dynamic Method Invocation which could work well here.

Consider this basic example comparing two strings. We supply .Compare() with an array which you could change as you need.

# Compare the two strings of mixed case
$strings = "F","f"
[string]::Compare.Invoke($strings)

# Compare the two strings of mixed case but set the ignore case flag
$strings = "F","f",$true
[string]::Compare.Invoke($strings)

Results for the above should be 1 then 0 as those strings only match when case is ignored.

Normally Compare() would return True or false. In this manner it just returns an integer where non-zero is for mismatched strings.

So lets try this out with your code.

$arguments = "Start","param1","param2","param3"
$excel.Run.Invoke($arguments)

I don't have an ideal setup to test this but it should work. Beware of return values might need to be handled differently via this approach. Test!

您可以使用如下参数运行宏:

$excel.Run('Workbookobject.Macroname', 'param1', 'param2', 'param3', ...)

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