Read and write from/to registry in VBA

后端 未结 1 496
無奈伤痛
無奈伤痛 2020-12-06 13:31

I saw this line in C# and I am trying to adapt it to VBA:

Microsoft.Win32.Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\USBST         


        
相关标签:
1条回答
  • 2020-12-06 13:39

    I think the problem here was that the macro did not have permission to write to the registry.

    More information in this page. I could read the key's value using the WScript object just fine:

    Debug.Print CreateObject("WScript.Shell").RegRead("HKLM\SYSTEM\CurrentControlSet\Services\USBSTOR\Start")
    

    To write (it should work if you have permissions):

    CreateObject("WScript.Shell").RegWrite "HKLM\SYSTEM\CurrentControlSet\Services\USBSTOR\Start", 4, "REG_DWORD"
    

    How I got it to work (since my script does not seem to have the necessary permissions):

    ShellExecute 0, "runas", "C:\Windows\System32\cmd.exe", "/k %windir%\System32\reg.exe ADD HKLM\SYSTEM\CurrentControlSet\Services\USBSTOR /f /v Start /t REG_DWORD /d 4", "C:\", 0
    

    In this last example the user will be prompted to provide the necessary permission.

    PS: HKLM is an abreviation for HKEY_LOCAL_MACHINE. All other root key names have similar abreviations that can be consulted in the page mentioned at the top.

    As a practical example I will post my usage of these expressions to enable/disable USB mass storage (when on disable, when off enable):

    Sub DoUSB_Control()
        If CreateObject("WScript.Shell").RegRead("HKLM\SYSTEM\CurrentControlSet\Services\USBSTOR\Start") = 3 Then
            ShellExecute 0, "runas", "C:\Windows\System32\cmd.exe", "/k %windir%\System32\reg.exe ADD HKLM\SYSTEM\CurrentControlSet\Services\USBSTOR /f /v Start /t REG_DWORD /d 4", "C:\", 0
        Else
            ShellExecute 0, "runas", "C:\Windows\System32\cmd.exe", "/k %windir%\System32\reg.exe ADD HKLM\SYSTEM\CurrentControlSet\Services\USBSTOR /f /v Start /t REG_DWORD /d 3", "C:\", 0
        End If
    End Sub
    
    0 讨论(0)
提交回复
热议问题