【问题标题】:Pass variable from PowerShell to VBA macro?将变量从 PowerShell 传递到 VBA 宏?
【发布时间】:2015-12-29 17:24:19
【问题描述】:

我有一个 PowerShell 脚本可以自动处理一些报告,并且我有许多单独的宏来执行非常相似的自动筛选功能,但标准不同。

是否可以将此条件从 PowerShell 传递到宏中?然后我可以只使用 1 宏。

ColNum = Application.Match("*header", Range("A1:Z1"), 0)

If Not IsError(ColNum) Then
    ActiveSheet.Range("A1").AutoFilter Field:=ColNum, Criteria1:="$criterafromPowerShell", Operator:=xlAnd
End If

我目前正在做类似的事情,但反过来,我将这些宏的输出插入工作簿并提取回 PowerShell,如下所示:

$counts = $workbook.worksheets.item(2)
$xRows = $counts.cells.item(1,1).Text
$yeRows = $counts.cells.item(1,2).Text

我承认我可以反过来做,并在文件打开之后和宏运行之前将我想在工作表中使用的文本插入,然后在宏中提取它......但是它看起来很乱。

有什么建议吗?

【问题讨论】:

  • 您必须创建一个带有参数的 UDF,使其成为公共范围,并使用 Application.Run 方法传递变量。 - 我认为...
  • 那么在 Excel/VBA 中创建一个函数并使用 Application.Run 从 PowerShell 调用它?我会做一些研究
  • 是的,iirc .Run() 方法是 Excel App 类的一部分,因此您可以执行 $xlApp.Run("'myWorkbook.xlsm'!Module1.MyUDF()", $arg1, $arg2) 之类的操作 - 语法可能不正确,但应该让您了解我在说什么
  • Application.Run (Excel) - MSDN 文章应该比我做得更好!
  • 明白了,我会读一读。非常感谢

标签: vba excel powershell


【解决方案1】:

例子:

$xlApp = New-Object -ComObject "Excel.Application"
$xlApp.Workbooks.Open("C:\Users\MacroMan\Documents\MyMacroWorkbook.xlsm")
$returnValue = $xlApp.Run("'MyMacroWorkbook.xlsm'!GenerateString", 6)
Echo $returnValue
FOOBAR

$returnValue = $xlApp.Run("'MyMacroWorkbook.xlsm'!GenerateString", 3)
Echo $returnValue
FOO

在“MyMacroWorkbook”(VBA)中:

Public Function GenerateString(strLength As Integer) As String
    GenerateString = Left("FOOBAR_SOMETHING", strLength)
End Function

【讨论】:

  • 大约 10 分钟前你在哪里我刚刚解决了 :) 感谢您提供这个示例,我可能会回来参考它!我的特定示例函数在引号中包含变量,我花了一些时间来计算“+ varName +”等。我也会添加它。
【解决方案2】:

我使用下面的代码从我的 VBscript 传递两个参数来打开一个特定的工作簿并启动所需的宏,你可以将你想要的变量作为变量传递给 sub,即Sub test(passedvariablehere) 并让 sub 考虑它:

'Create a WshShell to get the current directory
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")

If (Wscript.Arguments.Count < 2) Then 
  Wscript.Quit 
End If 

'retrieve the arguments

Dim strWorkerWB 
strWorkerWB = Wscript.Arguments(0) 

Dim strMacroName
strMacroName = Wscript.Arguments(1) 

' Create an Excel instance
Dim myExcelWorker
Set myExcelWorker = CreateObject("Excel.Application") 

myExcelWorker.Application.Visible = True

' Open the Workbook specified on the command-line 
Dim oWorkBook

Set oWorkBook = myExcelWorker.Workbooks.Open(strWorkerWB)

on error resume next 
' Run the calculation macro
myExcelWorker.Run strMacroName
if err.number <> 0 Then
   ' Error occurred - just close it down.
    oWorkBook.Close
    Set oWorkBook = Nothing
    myExcelWorker.Quit
    Wscript.Quit 
End If
err.clear

oWorkBook.Close
Set oWorkBook = Nothing

myExcelWorker.Quit

Set myExcelWorker = Nothing
Set WshShell = Nothing

on error goto 0 

第一个参数是工作簿的完整路径/名称,第二个参数是子名称

【讨论】:

  • 那么我将如何从 PowerShell 脚本中调用它呢?我不倾向于从命令行运行它,而是直接从 ISE 运行它。我会玩一会,看看我能走多远。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-12
相关资源
最近更新 更多