[英]Excel VBA Code Gives Error if Word Document is not already Open
抱歉,如果這是一個明顯的問題,但我遇到了一些 VBA 代碼的問題,該代碼試圖將一些數據從 word 文件導入 Excel 電子表格。 word文檔中有一些基本表格很好,但其中一個也在文本框中。 在這種情況下,我可以讓導入工作,但前提是 word 文件已經打開。 我不確定為什么會這樣。
如果有幫助,錯誤是:運行時錯誤、自動化錯誤、未指定錯誤。
wdFileName = Application.GetOpenFilename("Word files (*.doc*),*.doc*", , _
"Browse for file containing table to be imported")
If wdFileName = False Then Exit Sub '(user cancelled import file browser)
Set wdDoc = GetObject(wdFileName) 'open Word file
excelRow = Range("A" & Rows.Count).End(xlUp).Row + 1 ' find next blank row in excel spreadsheet based on column A
With wdDoc
TableNo = wdDoc.Tables.Count 'find total number of tables in the document
'This is the line that triggers the error if the word document is not already open, there are 7 shapes in the document for reference.
shpTableCount = .Shapes(4).TextFrame.TextRange.Tables.Count
感謝您的任何幫助,您可以提供。
GetOpenFilename
僅提供文件名GetObject
僅在該文件已打開時選擇該文件的 Word 實例。 如果它已關閉(意味着您在GetObject(wdFileName)
上遇到錯誤,您需要使用
Set wdDoc = Documents.Open(wdFileName)
所以你可以做
'check if it is already open
On Error Resume Next 'hide all error messages
Set wdDoc = GetObject(wdFileName)
On Error Goto 0 're-enable error messages
'if it is not open, then open it
If wdDoc Is Nothing Then
Set wdDoc = Documents.Open(wdFileName)
End If
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.