我尝试使用Excel中的VBA创建WordTemplate。在子例程中,我使用以下代码创建模板:
Set WdApp = New Word.Application
With WdApp
WordVersionNo = .Version
'Launch, activate and create new document:
.Visible = True
.Documents.Add
Call DelayInSeconds(5)
With .ActiveDocument
'Set up Page Layout
With .Sections(1).PageSetup
.Orientation = wdOrientPortrait
.TopMargin = CentimetersToPoints(2)
.BottomMargin = CentimetersToPoints(2)
.LeftMargin = CentimetersToPoints(2.5)
.RightMargin = CentimetersToPoints(2)
End With
'Select Language
.Range.LanguageID = wdEnglishUK
End With
With .Selection
'Write Letterhead Place Holder
.ParagraphFormat.Alignment = wdAlignParagraphLeft
.ParagraphFormat.LineSpacingRule = wdLineSpaceSingle
'Write Date Placeholder:
.ParagraphFormat.Alignment = wdAlignParagraphRight
.InsertDateTime datetimeformat:="d MMMM yyyy", insertasfield:=True, datelanguage:=wdEnglishUK
.TypeText vbNewLine
.ParagraphFormat.Alignment = wdAlignParagraphLeft
'Write Salutation:
.TypeText "Dear " & PlaceholderFormOfAddress & PlaceholderRecepientName & "," & vbNewLine & vbNewLine
'Some more stuff going on here (irrelevant)
End With
With .ActiveDocument
On Error GoTo SavingFailed
If WordVersionNo <= 12 Then
.SaveAs FileName:=ThisWorkbook.Path & "\" & TemplatesFolder & "\" & FileName, FileFormat:=wdFormatTemplate97
Else
.SaveAs2 FileName:=ThisWorkbook.Path & "\" & TemplatesFolder & "\" & FileName, FileFormat:=wdFormatTemplate
End If
On Error GoTo 0
End With
End With
'WdApp.Quit
Set WdApp = Nothing
如果我第一次运行它,代码运行得很好。但是,如果我再次运行它,我得到一个&#34;运行到错误462:当通过Excel VBA使用WORD时,远程服务器机器不存在&#34;错误。我已经阅读了微软关于此错误以及Running into Error 462: The remote server machine does not exist when working with WORD via Excel VBA的文档,但它对我来说太技术了。显然我正在引用一个&#34;悬空指针&#34;并消除引用的歧义将起作用。但是,我以为我已经通过嵌套语句识别了单词实例。