从网络获取的查找Word程序的VBA宏出现编译错误求助
解决VBA调用FindExecutable函数报错的问题
嘿,看你这段代码的问题,应该是Office版本适配的锅!你说找不到Word的可执行文件,想用这段代码定位,结果卡在API声明那行对吧?
先贴一下你提供的代码片段:
Sub FindExcelExe() MsgBox LocateExecutable("C:\WorkbookTest\Boktest2.xlsx") End Sub
报错的就是这个API声明部分:
Private Declare Function FindExecutable Lib "shell32" Alias "FindExecutableA" ( _ ByVal lpFile As String, _ ByVal lpDirectory As String, _ ByVal sResult As String _ ) As Long
问题根源
现在大部分人用的都是64位Office,而你这段声明是针对32位Office写的,没有加上PtrSafe关键字,64位环境下就会报错。另外,你代码里调用了LocateExecutable函数,但没给出实现,这也会导致运行失败。
修复后的完整代码
我给你调整成兼容32位和64位Office的版本,同时补上LocateExecutable的实现:
#If VBA7 Then Private Declare PtrSafe Function FindExecutable Lib "shell32.dll" Alias "FindExecutableA" ( _ ByVal lpFile As String, _ ByVal lpDirectory As String, _ ByVal lpResult As String _ ) As LongPtr #Else Private Declare Function FindExecutable Lib "shell32.dll" Alias "FindExecutableA" ( _ ByVal lpFile As String, _ ByVal lpDirectory As String, _ ByVal lpResult As String _ ) As Long #End If Sub FindWordExe() ' 要找Word的话,传一个docx格式的文件路径就行 MsgBox LocateExecutable("C:\Test\Sample.docx") End Sub Function LocateExecutable(strFilePath As String) As String Dim strResult As String Dim lngReturn As Variant ' 给结果字符串分配足够空间,避免溢出 strResult = String(255, vbNullChar) #If VBA7 Then lngReturn = FindExecutable(strFilePath, vbNullString, strResult) #Else lngReturn = FindExecutable(strFilePath, vbNullString, strResult) #End If ' 根据返回值判断调用是否成功 If lngReturn > 32 Then ' 去掉字符串末尾的空字符,提取有效路径 LocateExecutable = Left(strResult, InStr(strResult, vbNullChar) - 1) Else LocateExecutable = "未找到关联程序,错误代码:" & lngReturn End If End Function
小提示
- 我把原代码里的
FindExcelExe改成了FindWordExe,只要传入一个docx文件的路径,就能定位到Word的可执行程序; #If VBA7 Then的判断是为了同时兼容32位和64位Office,VBA7是Office 2010及以后版本的标识;- 返回值大于32表示调用成功,小于等于32对应不同的错误情况,比如32代表目标文件没有关联的程序。
内容的提问来源于stack exchange,提问作者DanDsc




