【问题标题】:Create Object for handling word on the fly (VBA)创建用于动态处理单词的对象(VBA)
【发布时间】:2017-02-06 13:06:57
【问题描述】:

我目前正在使用 VBA 通过添加对库的引用来创建 word 的实例,但这会导致问题,因为存在一些没有 word 的机器。

这会导致这些机器在启动时立即出现运行时错误。无法捕获此错误。

但是,我尝试通过类似这样的方式在 VBA 中动态创建一个对象

Dim oWshShell As WshShell
Set oWshShell = New WshShell
' *** TEST  REGESTRY
Dim tmp As String
tmp = oWshShell.RegRead("HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\15.0\Word\Options\PROGRAMDIR")
Debug.Print tmp

tmp = tmp + "winword.exe"

Dim oWord As Object
Set oWord = Shell(tmp)

但我的问题是 oWord 不是 Word.Application 的对象。那么如何处理呢?

如果能够使用 Word.Application 等所有功能,那就太好了。

【问题讨论】:

标签: vba ms-word


【解决方案1】:

你不必使用shell,直接使用COM工厂:

Function openWordApp() As Object
    On Error Resume Next
    Set openWordApp = CreateObject("Word.Application")
    If openWordApp Is Nothing Then
        msgBox "Word not installed on this machine"
    Else
        openWordApp.Visible = True
    End If
End Function

在调用者中,检查返回值是否Is Nothing

【讨论】:

    猜你喜欢
    • 2016-02-04
    • 2012-06-10
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 2012-09-07
    相关资源
    最近更新 更多