Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
784 views
in Technique[技术] by (71.8m points)

excel - Read and write from/to registry in VBA

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

Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesUSBSTOR", "Start", 4,Microsoft.Win32.RegistryValueKind.DWord);

I'm quite lost here with some error:

Runtime: 5 - invalid procedure call)

When I use the default i_Type string "REG_SZ" instead of "Start", then I get a regkey related error:

Runtime - -2147024891[80070005] invalid root

My code:

Dim i_RegKey As String, i_Value As String, i_Type As String
Dim myWS As Object
i_Type = "REG_SZ"  ' Optional
'access Windows scripting
Set myWS = CreateObject("WScript.Shell")
'write registry key
i_RegKey = "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesUSBSTORStart"
i_Value = "4"
i_Type = "REG_DWORD"
myWS.RegWrite i_RegKey, i_Value, i_Type
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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("HKLMSYSTEMCurrentControlSetServicesUSBSTORStart")

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

CreateObject("WScript.Shell").RegWrite "HKLMSYSTEMCurrentControlSetServicesUSBSTORStart", 4, "REG_DWORD"

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

ShellExecute 0, "runas", "C:WindowsSystem32cmd.exe", "/k %windir%System32
eg.exe ADD HKLMSYSTEMCurrentControlSetServicesUSBSTOR /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("HKLMSYSTEMCurrentControlSetServicesUSBSTORStart") = 3 Then
        ShellExecute 0, "runas", "C:WindowsSystem32cmd.exe", "/k %windir%System32
eg.exe ADD HKLMSYSTEMCurrentControlSetServicesUSBSTOR /f /v Start /t REG_DWORD /d 4", "C:", 0
    Else
        ShellExecute 0, "runas", "C:WindowsSystem32cmd.exe", "/k %windir%System32
eg.exe ADD HKLMSYSTEMCurrentControlSetServicesUSBSTOR /f /v Start /t REG_DWORD /d 3", "C:", 0
    End If
End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...