> 文章列表 > excel使用VBA获取能够打开指定文件的EXE程序

excel使用VBA获取能够打开指定文件的EXE程序

excel使用VBA获取能够打开指定文件的EXE程序

实现获取计算机中可以打开指定文件的EXE程序的代码

‘API声明

Declare Function FindExecutable Lib”shell32.dll” Alias “FindExecutableA” _

(ByVal lpFile As String, ByVal lpDirectory As String, ByVal lpResult AsString) As Long

Function ExePath(lpFile As String) As String

Dim lpDirectory As String

Dim strExePath As String

Dim lrc As Long

lpDirectory = “”

strExePath = Space(255)

lrc = FindExecutable(lpFile, lpDirectory, strExePath)

strExePath = Left$(strExePath, InStr(strExePath, Chr$(0)) – 1)

ExePath = strExePath

End Function

现在,我们要获取能够打开代码所在工作簿的Excel应用程序,使用代码:

MsgBox ExePath(ThisWorkbook.FullName)

结果如下图1所示

图1

也可以指定一个文件来获取其EXE程序,例如:

Sub Test_ExePath()

Dim strSpecFile As String

strSpecFile = “D:附件13g.pdf”

If ExePath(strSpecFile) = “” Then

MsgBox “没有发现本计算机中有这个文件的可执行程序.”,vbCritical, “错误”

Exit Sub

Else

MsgBox ExePath(strSpecFile)

End If

End Sub

运行后的结果如下图2所示。

图2