使用Excel查找Word文档中的单词时出现错误的文件名

时间:2016-01-07 21:36:26

标签: excel-vba ms-word syntax-error word-vba vba

我正在使用下面的代码在Excel电子表格中循环浏览一些数据并打开Word文档。我想循环浏览一个word文档,找到Excel工作表上的所有单词。这工作正常,直到我尝试在Excel工作表上找到单词,然后我收到“错误的文件名”消息。我突出显示了错误发生的下面一行。我确定这是一个语法错误,我只是不知道正确的语法是什么。谢谢你的帮助.......

    Dim MyDB() As String
    Dim MyCol() As String
    Dim MyDBCnt As Integer
    Dim MyColCnt As Integer
    Dim DBCnt As Integer
    Dim ResRow As Integer
    Dim r As Integer
    Dim x As Integer
    Dim PrevRow As Integer
    ResRow = 1
    r = 5
    x = 1
    PrevRow = 4

    Do Until Len(Trim(Cells(r, 4))) + Len(Trim(Cells(r, 5))) = 0
        DoEvents
        ReDim Preserve MyDB(1 To x)

       If (Trim(Cells(r, 4)) & "." & Trim(Cells(r, 5))) = (Trim(Cells(PrevRow, 4)) & "." & Trim(Cells(PrevRow, 5))) Then
'           do nothing
        Else
            MyDB(x) = Trim(Cells(r, 4)) & "." & Trim(Cells(r, 5))
            x = x + 1
        End If

        r = r + 1
        PrevRow = PrevRow + 1
    Loop

    x = x - 1
    MyDBCnt = x
    r = 5
    x = 1

    Do Until Len(Trim(Cells(r, 4))) + Len(Trim(Cells(r, 5))) = 0
        DoEvents
        ReDim Preserve MyCol(1 To x)
        MyCol(x) = Trim(Cells(r, 6))
        r = r + 1
        x = x + 1

    Loop

    x = x - 1
    MyColCnt = x

    Worksheets("Results").Activate
    MyLastRow = Cells.Find("*", [a1], , , xlByRows, xlPrevious).Row
    ResRow = MyLastRow

    Set WordApp = CreateObject("word.Application")
    Set WordDoc = WordApp.Documents.Open("R:\Report Web\SQL Doc.docx")
    WordApp.Visible = True
    WordDoc.Activate

    tmp = WordDoc.Name
    Dim j As Integer

    DBCnt = 1

    With WordApp.Selection
        Do Until DBCnt > MyDBCnt
            DoEvents
            With Documents(WordDoc).Find    ***ERROR OCCURS HERE
                .Text = MyDB(DBCnt)
                j = 0

                Do While .Execute(Forward:=True) = True
                    DoEvents
                    j = j + 1
                Loop
            End With

            If j > 0 Then
                MsgBox MyDB(DBCnt) & " was found " & j & " times."
            End If
            DBCnt = DBCnt + 1
        Loop
  End With

1 个答案:

答案 0 :(得分:1)

Find不是Document对象的有效属性。您需要在Selection或Range对象上使用它。例如:

Dim rngFind as Word.Range
Set rngFind = WordDoc.Content
With rngFind.Find

End With