用VBA检查某个软件是否安装及其安装路径
作者:互联网
用VBA检查某个软件是否安装及其安装路径
前言
有时候需要用VBA启动其它程序处理事情,例如整个处理流程中需要先解压缩文件。此时,主动探测用户电脑上是否已安装相应的软件及安装位置就比较重要。
实现
通过调用Windows API来实现
Private Declare Function RegOpenKeyEx Lib "advapi32.dll" Alias "RegOpenKeyExA" (ByVal hKey As Long, ByVal lpSubKey As String, ByVal ulOptions As Long, ByVal samDesired As Long, phkResult As Long) As Long
Private Declare Function RegQueryValueEx Lib "advapi32.dll" Alias "RegQueryValueExA" (ByVal hKey As Long, ByVal lpValueName As String, ByVal lpReserved As Long, lpType As Long, lpData As Any, lpcbData As Long) As Long
Private Declare Function RegCloseKey Lib "advapi32.dll" (ByVal hKey As Long) As Long
Private Const REG_SZ As Long = 1
Private Const KEY_QUERY_VALUE As Long = &H1
Private Const HKEY_LOCAL_MACHINE As Long = &H80000002
Function GetAppPath(ByVal AppName As String) As String
Dim hKey As Long
Dim lType As Long
Dim lSize As Long
Dim sSubKey As String
Dim sBuffer As String
sSubKey = "Software\Microsoft\Windows\CurrentVersion\App Paths\" & AppName
If RegOpenKeyEx(HKEY_LOCAL_MACHINE, sSubKey, 0, KEY_QUERY_VALUE, hKey) = 0 Then
If RegQueryValueEx(hKey, vbNullString, 0, lType, ByVal 0&, lSize) = 0 Then
If lType = REG_SZ And lSize > 0 Then
sBuffer = Space$(lSize)
If RegQueryValueEx(hKey, vbNullString, 0, lType, ByVal sBuffer, lSize) = 0 Then
GetAppPath = Trim(Replace(Trim(Left$(sBuffer, lSize - 1)), "\" & AppName, ""))
End If
End If
End If
End If
End Function
Sub Test()
Dim strAppPath as String
strAppPath = GetAppPath("7zFM.exe") '检查压缩软件7-Zip的安装路径,7-zip的程序名是7zFM.exe
If strAppPath = "" Then MsgBox "本电脑上没有安装7-Zip!"
End Sub
解释
关于advapi.dll,可以参考其它文章advapi.dll
标签:Dim,VBA,String,ByVal,路径,Long,hKey,lSize,安装 来源: https://blog.csdn.net/m0_54284125/article/details/120592672