繁体   English   中英

Excel VBA 如果 Word 文档尚未打开,则代码会出错

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM