【问题标题】:VBA Error handling, define an Error into an ErrorVBA 错误处理,将一个错误定义为一个错误
【发布时间】:2013-05-07 09:09:19
【问题描述】:

我通过 VBA 宏启动 Python。如果 Python 路径不好,我想要一个正确的错误消息。 我在 2 台不同的计算机上使用此宏,而这 2 台计算机上的 Python 路径并不相同。 2 条路径位于 2 个不同的单元格名称 path_Python 和 path_Python_2 这是我的代码:

Function launchPython() As Boolean
Dim pathScript As String

pathScript = [path_files] + "code.py"

On Error GoTo err
    Shell [path_Python].Value & " " & pathScript
    launchPython = True
    Exit Function

err:
    On Error GoTo err2
        Shell [path_Python_2].Value & " " & pathScript
        launchPython = True
err2:
    launchPython = False
    MsgBox "Error: please check Python paths"

End Function

问题是,当 2 条路径不好时,我没有进入 err2,而是在

上阻止了 VBA 错误消息
err:
    On Error GoTo err2
        Shell [path_Python_2].Value & " " & pathScript

我该如何解决这个问题? 非常感谢

【问题讨论】:

  • 您不能使用IF 语句而不是处理程序来验证路径吗?

标签: vba error-handling


【解决方案1】:

我不会尝试将命令发送到可能丢失的路径,而是检查文件是否存在并尝试。您可以使用许多函数之一,例如 http://allenbrowne.com/func-11.html 中的 FileExists,或者只检查 dir$ 是否返回非空白。

Dim Path as string

path = path_python

if dir(path) = "" then 
  path = path_python2
  if dir(path) = "" then err.raise
end if

shell path  & " " & pathScript

【讨论】:

    猜你喜欢
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 2019-02-21
    相关资源
    最近更新 更多