我正在尝试将对Word.Documents的引用传递给VBA中的sub(以便sub可以运行多次,总是使用相同的'target'word文档和不同的'source'文档)。
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
到目前为止,它似乎每次都没有错误地运行。
答案 0 :(得分: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
到目前为止,它似乎每次都没有错误地运行。