【问题标题】:Start application from VBA shell从 VBA shell 启动应用程序
【发布时间】:2015-01-24 11:06:01
【问题描述】:

在 excel 中,我试图插入一个按钮来将选定单元格的内容解析为新电子邮件。由于我使用的是 Mozilla Thunderbird,所以我必须通过 Shell 进行解析。 到目前为止我的代码:

    Dim dr As String
    If dir("C:\Program Files (x64)", vbDirectory) = "" Then
        dr = "C:\Program Files (x86)"
    Else
        dr = "C:\Program Files"
    End If
    dr = dr & "\Mozilla Thunderbird\thunderbird.exe"

    Dim args As String
    args = "to='" & MailTo & "',cc='" & MailCC & "',bcc='" & MailBCC & "'"
    args = args & ",subject='" & MailSubject & "',body='" & strbody & "'"
    If MailBijlage <> "" Then args = args & ",attachment='" & TempFilePath & TempFileName & ".pdf"

    Dim Command As String

    Command = "cmd.exe /S /K " & """" & dr & """" & " -compose " & """" & args & """"

    conf = MsgBox(Command, vbOKCancel, "Confirm command")

    If conf = vbOK Then
        Shell (Command)
        MsgBox "Email sent.", , "Info"
    ElseIf conf = vbCancel Then
        MsgBox "Canceled.", , "Info"
    End If

创建命令处理得很好,但是 Shell 不会启动 Thunderbird。它只是说:

'C:\Program' 未被识别为内部或外部命令, 可运行的程序或批处理文件。

不知道怎么回事,显示代码的消息框清楚地显示了路径周围的双引号。

提前致谢。

==编辑==

现在尝试使用批处理文件使其工作(如 S O 建议的那样)... 我打开了一个 bat 文件(已创建)并让 VBA 将命令输出到 bat 文件。 当我到达要求发送邮件的 msgbox 时,当我在记事本中打开 bat 文件时,它是空的。 VBA 调用空批处理文件,但没有任何反应(未发送邮件)。当我在宏结束后重新打开文件时,所有输出都在批处理文件中,当我运行它时,会按应有的方式编写邮件。

        Open Environ("userprofile") & "\desktop\tbmail.bat" For Output As #1
    If dir("C:\Program Files (x64)", vbDirectory) = "" Then
        Print #1, "cd ""%programfiles(x86)%"""
    Else
        Print #1, "cd ""%programfiles%"""
    End If
    Print #1, "cd ""Mozilla Thunderbird"""

        Print #1, "thunderbird.exe -compose """ & args & """"
    Close #1

    If conf = vbOK Then
        Call Shell(Environ("userprofile") & "\desktop\tbmail.bat")
        MsgBox "De mail is verstuurd.", , "Informatie"
    ElseIf conf = vbCancel Then
        MsgBox "Versturen geannuleerd.", , "Informatie"
    End If

怎么了?

【问题讨论】:

  • 您能否提供存储在名为“Command”的变量中的数据?另外,当您执行 Shell 时,您不需要 CMD.EXE 吗?见:stackoverflow.com/questions/2290365/…
  • 我做到了。首先创建变量 dr 并给出 Thunderbird 应用程序 (thunderbird.exe) 的绝对路径,并且 args 包含需要添加以从命令行撰写邮件的所有参数。不在Shell()中调用cmd.exe,会有什么不同吗?

标签: excel vba shell


【解决方案1】:

尝试将 cmd.exe 更改为 CMD

如果还是不行你可以试试:

CreateObject("WScript.Shell").Run Command, 1, False

如果要隐藏控制台,请将 1 更改为 0, 如果您希望在控制台中等待用户返回,请将 False 更改为 True。

或者你可以这样:

Open Environ("USERPROFILE") & "\desktop\test.bat" For Output As #1
Print #1, Command
Close #1
Shell Environ("USERPROFILE") & "\desktop\test.bat"
Kill Environ("USERPROFILE") & "\desktop\test.bat"

将命令写入批处理文件并使用Shell命令调用批处理文件。

我通常更喜欢使用 WScript.Shell 对象,因为它允许读取 StdOut 等非常有用的内容。

【讨论】:

  • cmd.exe 或者 CMD 没关系,还是一样的错误。 CreateObject 也给出了同样的错误。就好像传递给 cmd 的代码忽略了双引号。
猜你喜欢
  • 1970-01-01
  • 2018-08-20
  • 2017-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-20
  • 1970-01-01
相关资源
最近更新 更多