Tested in Excel 365 (16.8730.2046) 64-bit
DISCLAIMER: altering the registry could make your computer unusable. Make sure you know what you are doing! In case you use this code and damage you computer is your sole responsibility.
- Public Enum ENM_RegistryOperation
- RegistryRead
- RegistryWrite
- RegistryDelete
- End Enum
- '
- Public Enum ENM_RegistryKeyType
- REG_SZ
- REG_EXPAND_SZ
- REG_DWORD
- End Enum
- '
- Public Function ReadWriteDeleteRegistry(RegistryKeyAndPath As String, _
- Optional RegValue, Optional RegValueType As ENM_RegistryKeyType = REG_SZ, _
- Optional ReadWriteDelete As ENM_RegistryOperation = RegistryRead) As String
- Dim RegShell As Variant
- Dim KeyType As String
- Dim TempVal
- Select Case RegValueType
- Case REG_SZ
- KeyType = "REG_SZ"
- Case REG_EXPAND_SZ
- KeyType = "REG_EXPAND_SZ"
- Case REG_DWORD
- KeyType = "REG_DWORD"
- End Select
- Set RegShell = CreateObject("WScript.Shell")
- TempVal = ""
- Select Case ReadWriteDelete
- Case RegistryRead
- On Error Resume Next
- TempVal = RegShell.RegRead(RegistryKeyAndPath)
- On Error GoTo 0
- Case RegistryWrite
- RegShell.RegWrite RegistryKeyAndPath, RegValue, KeyType
- On Error Resume Next
- ' read it to confirm it was written and return as function value
- TempVal = RegShell.RegRead(RegistryKeyAndPath)
- On Error GoTo 0
- Case RegistryDelete
- TempVal = "Error"
- On Error Resume Next
- TempVal = RegShell.RegDelete(RegistryKeyAndPath)
- ' read it to confirm it was deleted
- TempVal = RegShell.RegRead(RegistryKeyAndPath)
- On Error GoTo 0
- ' the function will return "" for successful delete and "Error" for key not found.
- If TempVal <> "Error" Then TempVal = ""
- End Select
- ReadWriteDeleteRegistry = TempVal
- Set RegShell = Nothing
- End Function
- '
- Public Sub main()
- Dim a
- ' read example (Excel installation path)
- a = ReadWriteDeleteRegistry("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\16.0\Excel\InstallRoot\Path")
- ' or
- a = ReadWriteDeleteRegistry("HKLM\SOFTWARE\Microsoft\Office\16.0\Excel\InstallRoot\Path")
- Debug.Print a
- ' write example
- ' WARNING: make sure you don't write in the wrong place
- a = ReadWriteDeleteRegistry("HKEY_CURRENT_USER\Software\TestKey\TestVal", "testing", , RegistryWrite)
- ' or
- a = ReadWriteDeleteRegistry("HKCU\Software\TestKey\TestVal", "testing", , RegistryWrite)
- Debug.Print a
- ' delete example
- ' WARNING: make sure you delete the right one. Make some test with a key that you created
- a = ReadWriteDeleteRegistry("HKCU\Software\TestKey\TestVal", , , RegistryDelete)
- Debug.Print a
- End Sub