使用VBA读写Windows注册表( 二 )


3.DeleteSetting不能删除注册表项的缺省值 。
4.除非确定好了,否则不要随便删除注册表项设置,以免误删除导致严重的后果 。
示例
1.下面的代码将应用程序设置项写入注册表:
Sub TestControlReg()
SaveSetting “完美Excel”, _
“excelperfect\VBADev\MyPro”,_
“TestKey”, “100”
MsgBox “可以查看注册表了!”
End Sub
此时,打开注册表编辑器,导航到HKEY_CURRENT_USER\Software\VBand VBA Program Settings键下,会发现新增子键,如下图1所示 。

使用VBA读写Windows注册表


图1
2.下面的代码从注册表中获取指定注册表项值:
Sub TestControlReg1()
Dim val As Long
val = GetSetting(“完美Excel”, _
“excelperfect\VBADev\MyPro”,_
“TestKey”)
MsgBox val
End Sub
运行代码后的结果如下图2所示 。
使用VBA读写Windows注册表


图2
3.下面的代码删除指定键的注册表设置项名称:
Sub testCotrolReg2()
DeleteSetting “完美Excel”, _
“excelperfect\VBADev\MyPro”, _
“TestKey”
MsgBox “看看注册表!”
End Sub
4.下面是一段综合示例代码,演示了创建注册表项、更新注册表项、打印注册表项、打印所有注册表项、删除注册表项等操作 。
Sub testReg()
Dim vKeys As Variant
‘创建注册表项
SaveSetting “MyAppTest”,”General”, “MyApp_Name”, “完美Excel”
SaveSetting “MyAppTest”,”General”, “MyApp_Ver”, “1.0”
SaveSetting “MyAppTest”,”General”, “MyApp_Date”, “2019/10/17”
‘打印注册表项值
PrintRegSettings
‘更新注册表项
SaveSetting “MyAppTest”,”General”, “MyApp_Ver”, “1.1”
SaveSetting “MyAppTest”,”General”, “MyApp_Date”, “2019/10/20”
‘打印注册表项值
PrintRegSettings
‘获取并打印所有注册表项值
vKeys =GetAllSettings(“MyAppTest”, “General”)
PrintAllSettings vKeys
‘删除所有注册表项
DeleteSetting “MyAppTest”,”General”, “MyApp_Name”
DeleteSetting “MyAppTest”,”General”, “MyApp_Ver”
DeleteSetting “MyAppTest”,”General”, “MyApp_Date”
PrintRegSettings
End Sub
Sub PrintRegSettings()
Dim str As String
On Error Resume Next
str = “应用程序名称:” & _
GetSetting(“MyAppTest”,”General”, “MyApp_Name”) & _
vbCrLf & “应用程序版本:” &_
GetSetting(“MyAppTest”,”General”, “MyApp_Ver”) & _
vbCrLf & “更新日期:” &_
GetSetting(“MyAppTest”,”General”, “MyApp_Date”)
MsgBox str
End Sub
Sub PrintAllSettings(vSettings As Variant)
Dim i As Integer
If IsArray(vSettings) Then
For i = 0 To UBound(vSettings)
Debug.Print vSettings(i, 0) &”: ” & _
vSettings(i, 1)
Next i
End If
End Sub
【使用VBA读写Windows注册表】有兴趣的朋友可以自已动手实践一下上述测试程序,以此来熟悉VBA中的这几个操控注册表的函数 。

猜你喜欢