The Function to Set a Key Value
The next procedure, SetKeyValue(), wraps both RegOpenKeyEx and RegSetValueEx functions to open the subkey and set its value, respectively. After each function call, it checks that the call completed successfully, and if not, raises a custom error and returns a Boolean False. If the call completes successfully, it returns a Boolean True.
Public Function SetKeyValue(lngRootKey As w32Key, _ strSubKey As String, _ strValueName As String, _ strNewValue As String) _ As Boolean
Dim hKey As Long
Dim lngSize As Long
On Error GoTo SetKeyValue_Err
'Open the key and get its handle lngReturn = RegOpenKeyEx(lngRootKey, strSubKey, _ 0&, KEY_WRITE, hKey)
'Check that the call succeeded If lngReturn <> ERROR_SUCCESS Then
Err.Raise vbObjectError + 2, , "Could not open key." End If
'Initialize the size variable lngSize = Len(strNewValue)
'Set the key value lngReturn = RegSetValueEx(hKey, _
ByVal strNewValue, _ lngSize)
'Check that the call succeeded If lngReturn <> ERROR_SUCCESS Then
Err.Raise vbObjectError + 3, , "Could not save value." End If
SetKeyValue_Exit:
On Error Resume Next
'Return success or failure
SetKeyValue = (lngReturn = ERROR_SUCCESS)
'Close the key lngReturn = RegCloseKey(hKey) Exit Function
SetKeyValue_Err: DoCmd.Beep
MsgBox "Error " & Err.Number & vbCrLf & _
Err.Description, vbOKOnly + vbExclamation, _ "Could not save the key value"
Resume SetKeyValue_Exit End Function
Post a comment