VBA用于根据单元格值打开word文档的功能

时间:2018-02-20 11:05:25

标签: excel-vba vba excel

让这个功能正常工作有一些小问题。它目前能够根据检查单元格值是否存在来识别文件,但问题是它实际上并没有打开单词文档。

非常感谢任何帮助。

Public Function Method2(ByVal rngl As Range, ByVal strSearch As Variant, ByVal sPath As String)

Dim directory As String

Dim fileName As String

Dim myFile As File

Dim FSO As New FileSystemObject

Dim myFolder As Folder

Dim mySubFolder As Folder

Dim objWord

Dim objDoc

Dim rngRange

Dim rng1 As Range

Set myFolder = FSO.GetFolder(sPath)


directory = "S:\File Recipes\"

fileName = "Yaroze_Test"

Set objWord = CreateObject("Word.Application")

    Set rng1 = Range("A:A").find(strSearch, , xlValues, xlWhole)
    If strSearch = "" Then
    MsgBox "Please Enter a Product Code!"
    Exit Function
    End If
    If Not rng1 Is Nothing Then

        MsgBox "Product Codes Found!"
        For Each mySubFolder In myFolder.SubFolders

            For Each myFile In mySubFolder.Files

                If InStr(myFile, strSearch) > 0 Then

                fileName = myFile.Name

                MsgBox (myFile.Name)

                Do While fileName <> ""

                    ChDrive ("S")

                    ChDir ("S:\File Recipes\")

                    directory = mySubFolder.Path & "\" & fileName

                    MsgBox directory

                    objWord.Documents.Open fileName:=directory

                    DoEvents

                    Exit For



                Loop

                MsgBox "Task Complete!"

                objWord.Visible = True

                End If

            Next

        Next
       ' Set rngRange = _
         objWord.Range(objWord.Paragraphs(1).Start, objWord.Paragraphs(1).End - 1)
       ' rngRange.InsertAfter _
         "This is now the last sentence in paragraph one."
        Else
            MsgBox "Product Codes Not Found!"
        End If

End Function

我认为问题在于:

objWord.Documents.Open fileName:=directory

但我无法确定。

1 个答案:

答案 0 :(得分:0)

当我测试这个时,我发现它导致excel永远等待Word完成ole动作。我在objWord.Visible = True之前移动了objWord.Documents.Open Filename:=directory后发现Word在尝试打开文件时给了我一个提示。

如果您在objWord.Visible = True之前移动objWord.Documents.Open Filename:=directory,也可能与您相同。