Checking for Office applications in Visual Basic
Thursday, 16 November 2006
I recently got an email from one of our readers who found our Spellchecking from Visual Basic article useful but wanted to know if there was a way to ensure that Microsoft Word was installed before attempting to invoke the spellchecking function.
The short answer is “yes, there is”. The actual VB6 code required isn’t all that much but you’ll have to call the Windows API to do it. Put the following code into a module and name it something meaningful:
Private Declare Function RegOpenKey Lib "advapi32" Alias _
"RegOpenKeyA" (ByVal Key As Long, ByVal SubKey As String, _
Result As Long) _
As Long
Private Declare Function RegQueryValueEx Lib "advapi32" Alias _
"RegQueryValueExA" (ByVal Key As Long, ByVal ValueName As String, _
Reserved As Long, KeyType As Long, Buffer As Any, _
BufferSize As Long) _
As Long
Private Declare Function RegCloseKey Lib "advapi32" (ByVal Key As Long) _
As Long
Private Const REG_SZ = 1
Private Const REG_EXPAND_SZ = 2
Private Const ERROR_SUCCESS = 0
Private Const HKEY_CLASSES_ROOT = &H80000000
Private Function GetRegString(Key As Long, SubKey As String, _
ValueName As String) As String
Dim Setting As String, Lth As Long, Res As Long
If RegOpenKey(Key, SubKey, Res) = ERROR_SUCCESS Then
Setting = Space(255)
Lth = Len(Setting)
If RegQueryValueEx(Res, ValueName, ByVal 0, REG_EXPAND_SZ, _
ByVal Setting, Lth) = ERROR_SUCCESS Then
If Lth > 1 Then
GetRegString = Left(Setting, Lth - 1)
End If
End If
RegCloseKey Res
End If
End Function
Private Function IsAppInstalled(ByVal SubKey As String, _
ByVal ValueName As String) _
As Boolean
IsAppInstalled = CBool(Len(GetRegString(HKEY_CLASSES_ROOT, _
SubKey, ValueName)))
End Function
Public Function IsAccessInstalled() As Boolean
IsAccessInstalled = IsAppInstalled("Access.Application\CurVer", _
"")
End Function
Public Function IsExcelInstalled() As Boolean
IsExcelInstalled = IsAppInstalled("Excel.Application\CurVer", _
"")
End Function
Public Function IsOutlookInstalled() As Boolean
IsOutlookInstalled = IsAppInstalled("Outlook.Application\CurVer", _
"")
End Function
Public Function IsPowerpointInstalled() As Boolean
IsPowerpointInstalled = IsAppInstalled("PowerPoint.Application\CurVer", _
"")
End Function
Public Function IsWordInstalled() As Boolean
IsWordInstalled = IsAppInstalled("Word.Application\CurVer", _
"")
End Function
Alternatively, you could put all the above in a class module and change all the public functions to “get” properties instead. The actual public functions which would be called from anywhere in your application are:
IsAccessInstalled()
IsExcelInstalled()
IsOutlookInstalled()
IsPowerpointInstalled()
IsWordInstalled()
For those wishing to learn more about integrating their VB applications with Microsoft Office, the bad news is that there’s not much information on the web. The good news is that you should still be able to pick up a copy of the excellent Steve Brown book Visual Basic 6 Complete.
|