Use VBA to check whether a certain software is installed and its installation path
foreword
Sometimes you need to use VBA to start other programs to handle things, for example, you need to decompress files first in the entire processing process. At this time, it is more important to actively detect whether the corresponding software and the installation location have been installed on the user's computer.
accomplish
Implemented by calling the 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
explain
About advapi.dll, you can refer to other articles advapi.dll