使用Excel VBA查找注册表项

时间:2016-03-11 09:42:12

标签: excel vba registry

我想检查用户是否安装了Microsoft SQL Native Client 2008(sqlncli10)或Native Client 2012(sqlncli11)。

Dim key As String
Dim myShell As Object
Set myShell = CreateObject("WScript.Shell")

key = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\SQLNCLI11\CurrentVersion\Version"
'key = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\CurrentVersion"

Dim strKey As String
strKey = myShell.RegReadkey(key)

在查找本机客户端时,我收到错误:

  

注册表项“HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft SQL Server \ SQLNCLI11 \ CurrentVersion \ Version”中的根目录无效

但是在尝试Windows NT版本时,它可以正常工作。

我用HKLM替换了HKEY_LOCAL_MACHINE:但这也不起作用。

编辑

我想我想的就是这样。当我在注册表中签入时,它存在于64位部分中。但是,VBA检查为32位,而SOFTWARE的根目录为Wow6432Node。所以它检查Wow6432Node \ Microsoft \ Microsoft SQL Server并且那里不存在密钥。但我找到了另一个路径SOFTWARE \ Microsoft \ Microsoft SQL Server Native Client 10或11,它们都存在于32位和64位中。

2 个答案:

答案 0 :(得分:0)

此代码适用于我:

Dim key As String
Dim objShell As Object

Set objShell = CreateObject("WScript.Shell")
key = objShell.RegRead _
    ("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\SQLNCLI11\CurrentVersion\Version")

我刚刚在Excel 2010 VBA编辑器中执行了此操作。

答案 1 :(得分:0)

使用下面的函数代替WScript。这将同时适用于32位和64位。

Function ReadRegistry(RootKey, Key As String, Value As String, Optional RegType As Integer = 32) As String


    ' Reads a REG_SZ value from the local computer's registry using WMI.
    ' Parameters:
    '   RootKey - The registry hive (see http://msdn.microsoft.com/en-us/library/aa390788(VS.85).aspx for a list of possible values).
    '   Key - The key that contains the desired value.
    '   Value - The value that you want to get.
    '   RegType - The registry bitness: 32 or 64.


    Dim oCtx, oLocator, oReg, oInParams, oOutParams

    Set oCtx = CreateObject("WbemScripting.SWbemNamedValueSet")
    oCtx.Add "__ProviderArchitecture", RegType

    Set oLocator = CreateObject("Wbemscripting.SWbemLocator")
    Set oReg = oLocator.ConnectServer("", "root\default", "", "", , , , oCtx).Get("StdRegProv")

    Set oInParams = oReg.Methods_("GetStringValue").InParameters
    oInParams.hDefKey = RootKey
    oInParams.sSubKeyName = Key
    oInParams.sValueName = Value

    Set oOutParams = oReg.ExecMethod_("GetStringValue", oInParams, , oCtx)

    ReadRegistry = oOutParams.sValue
End Function

Sub test()
  Const HKEY_CURRENT_USER = &H80000001
  MsgBox ReadRegistry(HKEY_CURRENT_USER, "Software\Microsoft\Office\15.0\Outlook\Security", "OutlookSecureTempFolder")
End Sub