我正在创建一个Excel工作表来搜索数据库中的单词(.docx)文档,然后我想打开它们。如果是电子表格,我可以找到该文件并将其打开。但我不能打开单词文件?我在" objWord.documents.Open xFile"中出现了不匹配错误。行,任何答案??
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 :(得分: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