1

我正在尝试将对 Word.Documents 的引用传递给 VBA 中的子程序(以便子程序可以运行多次,始终使用相同的“目标”word 文档和不同的“源”文档)。

Public Sub StructuredFileParse(wrdDocSource As Word.Document, _
                            Optional wrdDocTarget As Word.Document = Nothing)

Dim wrdApp As Object

Set wrdApp = wrdDocSource.Application

If wrdDocTarget Is Nothing Then
    Set wrdDocTarget = wrdApp.Documents.Add
End If

wrdDocTarget.Activate
With wrdApp.Selection.PageSetup
    .LeftMargin = CentimetersToPoints(2#) 'Code fails here second time it runs
    .RightMargin = CentimetersToPoints(2#)
End With

'Do stuff

Set wrdApp = Nothing

End Sub

Public Sub TestSub()

Const ERR_APP_NOTFOUND As Long = 429

Dim wrdApp As Word.Application

Dim wrdDocSource As Word.Document
Dim wrdDocTarget As Word.Document

On Error Resume Next
' Attempt to reference running instance of Word.
Set wrdApp = GetObject(, "Word.Application")
' If Word isn't running, create a new instance.
If Err = ERR_APP_NOTFOUND Then
   Set wrdApp = New Word.Application
End If
On Error GoTo 0

wrdApp.Visible = True

'Create a new word target file
Set wrdDocTarget = wrdApp.Documents.Add

'Set the first word source file
Set wrdDocSource = wrdApp.Documents.Open(ThisWorkbook.Path & "\" & _
                    "AdvisorChargeQuoteSource.dot")

Call StructuredFileParse(wrdDocSource:=wrdDocSource, wrdDocTarget:=wrdDocTarget)

wrdDocSource.Close

Set wrdDocSource = Nothing
Set wrdDocTarget = Nothing
Set wrdApp = Nothing
End Sub

我第一次调用 sub 时,一切都按预期工作。然而,我第二次在上面的 PageSetup 部分的末尾收到错误(没有错误文本,只有一个 Ok/Help 窗口和执行停止)。

任何人都可以突出错误吗?

谢谢

史蒂夫

编辑:在http://support.microsoft.com/kb/189618找到的解决方案

改变了

With wrdApp.Selection.PageSetup
    .LeftMargin = CentimetersToPoints(2#) 'Code fails here second time it runs
    .RightMargin = CentimetersToPoints(2#)
End With

With wrdApp.Selection.PageSetup
    .LeftMargin = wrdApp.CentimetersToPoints(2#)
    .RightMargin = wrdApp.CentimetersToPoints(2#)
End With

到目前为止,它似乎每次运行都没有错误。

4

1 回答 1

0

在http://support.microsoft.com/kb/189618找到的解决方案

改变了

With wrdApp.Selection.PageSetup
    .LeftMargin = CentimetersToPoints(2#) 'Code fails here second time it runs
    .RightMargin = CentimetersToPoints(2#)
End With

With wrdApp.Selection.PageSetup
    .LeftMargin = wrdApp.CentimetersToPoints(2#)
    .RightMargin = wrdApp.CentimetersToPoints(2#)
End With

到目前为止,它似乎每次运行都没有错误。

于 2013-02-25T09:57:27.083 回答