VBA将双引号传递给Powershell字符串

时间:2018-12-13 12:59:09

标签: vba powershell

我正在尝试创建一个字符串,在其中我需要使用一些双引号,我尝试了多种方法来执行此操作,但是所有操作都给我一个错误,请问有人可以帮助我吗?

Public Sub Script2()
    Dim ScriptText As String
    ScriptText = "[System.Windows.Forms.MessageBox]::Show(""""Message Text"""",""""Title"""",1)"
    Call shell("PowerShell -noexit powershell.exe  -Executionpolicy Bypass -Command " & ScriptText, vbNormalFocus)
End Sub

如果我这样尝试,我会得到:

Message : The term 'Message' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
    No line:1 character:88
    + ... ypass -Command[System.Windows.Forms.MessageBox]::Show(Message Text,Ti ...
    +                                                           ~~~~~~~
        + CategoryInfo          : ObjectNotFound: (Message:String) [], CommandNotFoundException
        + FullyQualifiedErrorId : CommandNotFoundException

3 个答案:

答案 0 :(得分:1)

好的,这是一个工作代码(它是VBS,但在VBA中使用它应该不会有很多麻烦)

ScriptText = """[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Message Text','Title',1)"""
createobject("wscript.shell").run "powershell.exe  -noexit -Executionpolicy Bypass -Command " & ScriptText

答案 1 :(得分:0)

您是否尝试过对所需的每个对象使用`?这样您将获得如下信息:

ScriptText = "[System.Windows.Forms.MessageBox]::Show(`"`"Message Text`"`",`"`"Title`"`",1)"

"通常是保留的,如果您需要将其写入字符串中,则需要对其进行转义。

答案 2 :(得分:0)

您有两个级别的参数扩展(一个是VBA,一个是Powershell),因此您需要双引号。加倍的双引号使它超过了VBA。反引号将使其转为Powershell。

ScriptText = "[System.Windows.Forms.MessageBox]::Show(`""Message Text`"",`""Title`"",1)"