首页 > 解决方案 > 命令不可用,因为没有打开的文档

问题描述

我正在尝试使用宏从excel中某些word文档中的表中导入一些数据,但是当打开word文档并从excel宏中读取它时,我无能为力,因为它说我没有打开文件,但我愿意。

如果我打开一个文档,只用它的名字来调用它,那没关系,但是当我从搜索和循环中打开文件时,问题就来了。

Sub LoopFile()

    Dim MyFile, MyPath As String
    Dim wrdApp, wrdDoc
    MyPath = "here goes my path with personal info, it points to a folder"
    MyFile = Dir(MyPath)
    Set wrdApp = CreateObject("Word.Application")
    Do While MyFile <> ""

'parameters for the files to search

        If MyFile Like "*.docx" And MyFile Like "All*" Then
            wrdApp.Visible = True
            Set wrdDoc = wrdApp.Documents.Open(MyPath & MyFile)
            Call GetID
            wrdApp.Close
        End If
        MyFile = Dir
    Loop
End Sub


Sub GetId()

    Dim cicli, y As Integer
    'counter for iterations
    cicli = cicli + 1
    'if it's first iteration it starts from column E, otherwise the next one
    If (cicli = 1) Then
        y = 5
    Else
        y = y + 1
    End If

    ActiveDocument.Tables(1).Cell(Row:=1, Column:=2).Range.Copy
    ThisWorkbook.Worksheets("Foglio1").Cells(23, y).PasteSpecial xlPasteValues


End Sub

当它到达时问题就来了

ActiveDocument.Tables(1).Cell(Row:=1, Column:=2).Range.Copy

我该如何解决?谢谢

标签: excelvbams-word

解决方案


传递您所指的文档并避免ActiveDocument. 例如,尝试以如下方式修复它:

Set wrdDoc = wrdApp.Documents.Open(MyPath & MyFile)
GetID wrdDoc

然后改变一点GetId Sub,接受wrdDoc参数。

Sub GetId(wrdDoc as Object)

    Dim cicli, y As Integer
    'counter for iterations
    cicli = cicli + 1
    If (cicli = 1) Then
        y = 5
    Else
        y = y + 1
    End If

    wrdDoc.Tables(1).Cell(Row:=1, Column:=2).Range.Copy
    ThisWorkbook.Worksheets("Foglio1").Cells(23, y).PasteSpecial xlPasteValues

End Sub

如何避免在 Excel VBA 中使用 Select


推荐阅读