excel VBA中有没有一种方法可以从文件夹中查找文件并打开它?
Here's an example of how you could use CMD to do this in Excel-VBA:
Sub FindFile()
Dim fileName As String
Dim parentFolder As String
Dim found As String
parentFolder = "C:\Users\Macro Man\Documents\" '// 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
It uses a DIR
command to find the file (the /S
parameter specifies that it should look through all sub-directories) and then uses the START
command to open the file in it's native application.
here you can find another example on how to search in folders:
Is it possible to list all the files and folders in a custom directory - excel vba
the example lists all files in a given folder and all sub folders.
and here an example on how you can open a text file and search for given values for example:
MS VB For Application - Read href value in a txt file
If you specify more precise what you need we can probably give more specific answers.
if by "find" you mean open a file with a specific name, then you can simple do it like this:
Filename = "sampleFile.xlsx"
Application.Workbooks.Open ("d:\sample\path\" + Filename)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.