2017-04-20 9 views
1

データベース(.docx)文書を検索するためのExcelシートを作成しています。スプレッドシートの場合はファイルを見つけて開くことができます。しかし、私は単語の文書を開くことができない?私は、 "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

答えは、ファイルパスをセルに保存してから、ファイルパスからワードドキュメントを開くための新しいサブを作成することでした。シンプルだが誰かが興味を持っている場合は以下を参照。

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 
関連する問題