在excel VBA中有没有办法从文件夹中找到文件并打开它?
以下是如何在Excel VBA中使用CMD:执行此操作的示例
Sub FindFile()
Dim fileName As String
Dim parentFolder As String
Dim found As String
parentFolder = "C:UsersMacro ManDocuments" '// Note the trailing "" this is required!
fileName = "findMe.html" '// Change as required
With CreateObject("WScript.Shell")
found = CStr(Split(.Exec("CMD /C DIR """ & parentFolder & "*" & fileName & """ /S /B /A:-D").StdOut.ReadAll, vbCrLf)(0))
If Not Trim(found) = "" Then
.Run "CMD /C START """ & Trim(found) & """", 0, True
Else
MsgBox "File not found!", vbInformation
End If
End With
End Sub
它使用DIR
命令查找文件(/S
参数指定它应该查找所有子目录),然后使用START
命令在其本机应用程序中打开文件。
在这里,您可以找到另一个关于如何在文件夹中搜索的示例:
是否可以列出自定义目录中的所有文件和文件夹-excel vba
该示例列出了给定文件夹中的所有文件和所有子文件夹。
这里有一个关于如何打开文本文件并搜索给定值的示例,例如:
MS VB For Application-读取txt文件中的href值
如果你更准确地说明你需要什么,我们可能会给出更具体的答案。
如果你所说的"find"是指打开一个具有特定名称的文件,那么你可以简单地这样做:
Filename = "sampleFile.xlsx"
Application.Workbooks.Open ("d:samplepath" + Filename)