了解 If Err.Number 的使用

Understanding Use of If Err.Number

我有一个 vba 宏,它从 excel sheet 中获取信息并填充一个 word 文档。在宏的开头,我使用找到的代码来定义单词 document/application.

的变量
Dim WRD As Object, DOC As Object
On Error Resume Next
Set WRD = CreateObject("Word.Application")
If Err.Number <> 0 Then
    Set WRD = CreateObject("Word.Application")
End If
On Error GoTo 0

' Setting the correct word document template

Set DOC = WRD.Documents.Open(ThisWorkbook.Path & "\template.docx", ReadOnly:=True)

WRD.Visible = True

这一切都很好地工作,但是我试图完全理解我正在使用的代码,但我不知道为什么我有

Set WRD = CreateObject("Word.Application")
If Err.Number <> 0 Then
    Set WRD = CreateObject("Word.Application")
End If

我查过 Err.Number 是什么,但为什么 WRD = CreateObject("Word.Application") 与它一起使用了两次。

您的代码不正确。应该是:

Dim WRD As Object, DOC As Object
'ignore errors to prevent generic error message being displayed
On Error Resume Next
'attempt to get the currently open instance of Word
Set WRD = GetObject(,"Word.Application")
'If Word isn't open an error is generated
If Err.Number <> 0 Then
    'as Word wasn't already open create a new instance
    Err.Clear
    Set WRD = CreateObject("Word.Application")
End If
'reset error handling as errors should not be ignored
On Error GoTo 0