good VB application should always check that its components are correctly registered before using them. The registration step is usually quite fast, so you might decide to re-register your DLLs or ActiveX controls when your application starts, as a precautionary rule. The problem is that there is no obvious way to do so from within VB. The following tip shows how.
The Tip Bank contains several other tips for advanced techniques with ActiveX DLLs, such as getting the Command string from inside a DLL, passing a DLL the VBA's hidden Global object, and how to rebase a compiled DLL. We provide also a .REG file that lets you register and unregister DLLs via a popup menu in Explorer.
Here's the tip:
All ActiveX DLLs or OCXes export two functions DllRegisterServer and DllUnregisterServer. They are used to register and unregister the ActiveX component in the Windows registry, and are usually invoked from regsvr32.exe at registration time.
However, you can register and unregister these files programmatically whenever you want to, provided that you know the name of the DLL or OCX at compile time. All you have to do is prepare two aliased functions, as in the following example, that show how to register and unregister the COMCTL32.OCX file:
'function to call to register the ActiveX
Private Declare Function RegComCtl32 Lib "COMCTL32.OCX" Alias _
"DllRegisterServer" () As Long
' function to call to unregister the ActiveX
Private Declare Function UnRegComCtl32 Lib "COMCTL32.OCX" Alias _
"DllUnregisterServer" () As Long
Const ERROR_SUCCESS = 0&
Note that the two functions work only if the DLL is in the system path or in the current directory. Therefore, if you want to register a DLL located outside system directories, you must use ChDrive and ChDir commands to make that directory the current one.
For example, say that you have a Test.DLL file in the C:\MyApp directory. Here's the code that registers it:
Private Declare Function RegisterTestDLL Lib "Test.Dll" _
Alias "DllRegisterServer" () As Long
Dim retCode As Long
On Error Resume Next
' move to the DLL's directory
ChDrive "C:"
ChDir "C:\MyApp"
' register the DLL
retCode = RegisterTestDLL()
If Err <> 0 Then
' probably the DLL isn't there
MsgBox "Unable to find the Test.Dll file"
ElseIf retCode <> ERROR_SUCCESS Then
' the registration run but failed
MsgBox "Registration failed"
End If