2017-04-20 76 views
1

我正在創建一個Excel表格來搜索單詞(.docx)文檔的數據庫,然後我想打開它們。如果是電子表格,我可以找到該文件並將其打開。但我不能讓文檔打開?在「objWord.documents.Open xFile」一行中出現不匹配錯誤,任何答案?從Excel中搜索和打開Word文檔

Private Sub CommandButton1_Click() 
Call FindFile 
End Sub 

Sub FindFile() 

Dim xFile As File 
Dim xFolder As Folder 
    Set Fsys = CreateObject("Scripting.FileSystemObject") 
    Set ObjFolder = Fsys.GetFolder("File Folder") 

For Each xFolder In ObjFolder.SubFolders 
    If FindFiles(xFolder) = True Then Exit Sub 
    If FindFolder(xFolder) = True Then Exit Sub 
Next 
    Set Fsys = Nothing 
    MsgBox "File not found.." 

End Sub 

Function FindFolder(FolderPath As Folder) As Boolean 
Dim RootFolder As Folder 
For Each RootFolder In FolderPath.SubFolders 
    If FindFiles(RootFolder) = True Then 
     FindFolder = True 
     Exit Function 
    End If 
    Call FindFolder(RootFolder) 
Next 
End Function  
Function FindFiles(xFolder As Folder) As Boolean 

Dim xFile As File 
For Each xFile In xFolder.Files 

     FindFiles = False 

    If LCase(xFile.Name) = LCase(Range("B2").Value) Then 
    Set objWord = CreateObject("Word.Application") 
     objWord.Visible = True 
     objWord.documents.Open xFile 

     FindFiles = True 

       FindFiles = True 
     Exit Function 
    End If 

Next 
End Function 

回答

0

於是通過多方考察,得到的答覆是,將文件保存路徑在一個單元格,然後創建一個新的子從文件路徑打開Word文檔。很簡單,但如果有人感興趣,請看下面

Private Sub CommandButton1_Click() 
Call FindFile 
Call Open_Word_Document 
End Sub 

Sub FindFile() 

Dim xFile As File 
Dim xFolder As Folder 

Range("B9").ClearContents 

Set Fsys = CreateObject("Scripting.FileSystemObject") 

Set ObjFolder = Fsys.GetFolder("Folder Path") 

For Each xFolder In ObjFolder.SubFolders 
    If FindFiles(xFolder) = True Then Exit Sub 
    If FindFolder(xFolder) = True Then Exit Sub 
Next 

If IsEmpty(Range("B9").Value) = True Then 

MsgBox "Diary doesnt exist, have you had your head checked lately!" 
End 
End If 
End Sub 

Function FindFolder(FolderPath As Folder) As Boolean 
Dim RootFolder As Folder 
For Each RootFolder In FolderPath.SubFolders 
    If FindFiles(RootFolder) = True Then 
     FindFolder = True 
     Exit Function 
    End If 
    Call FindFolder(RootFolder) 
Next 
End Function 

Function FindFiles(xFolder As Folder) As Boolean 

Dim xFile As File 
For Each xFile In xFolder.Files 

     FindFiles = False 

    If LCase(xFile.Name) = LCase(Range("B8").Value) Then 
     Sheets("Sheet1").Range("B9").Value = xFile.Path 


     FindFiles = True 

     Exit Function 
    End If 

Next 
End Function 

Sub Open_Word_Document() 
'Opens a Word Document from Excel 

' Define Word object. 
Dim objWord As Object 
' Create Word instance. 
Set objWord = CreateObject("Word.Application") 
'Load the file named in Cell B9. 
objWord.Documents.Open Range("B9").Value 
'Make Word visible. 
objWord.Visible = True 

End Sub