# RegQueryValueEx Function

`Declare Function RegQueryValueEx Lib "advapi32.dll" Alias "RegQueryValueExA" (ByVal hKey As Long, ByVal lpValueName As String, ByVal lpReserved As Long, lpType As Long, lpData As Any, lpcbData As Long) As Long`
Alternate Declare for use with strings:
`Declare Function RegQueryValueEx Lib "advapi32.dll" Alias "RegQueryValueExA" (ByVal hKey As Long, ByVal lpValueName As String, ByVal lpReserved As Long, lpType As Long, ByVal lpData As String, lpcbData As Long) As Long`

RegQueryValueEx reads a value from a registry key. It can read many different types of data. Notice that a variant of the declare must be used if a type of string is being read because of the way Visual basic handles strings. The only difference is the method in which the string is passed to the API function. The function returns 0 if successful, or a non-zero value error code if an error occured.

hKey
  A handle to the registry key to read the value from. This cannot be one of the predefined (HKEY_) keys.
lpValueName
  The name of the value to read.
Reserved
  Reserved. Set to 0.
lpType
  Variable which receives the registry data type of the piece of data to read.
lpData
  Variable or whatever object receives the information read from the registry. NOTE: You must use the alternate declare for any type of string when using Visual Basic!
lpcbData
  Receives the length in bytes of the data returned. If a type of string is used, set this variable to the length in bytes of the string passed as lpData.

Example:

    ' Read some data from under the key:
    ' HKEY_CURRENT_USER\Software\Dummy\DummyApp\1.0\
    Dim dword As Long, vbstring As String * 100, datatype As Long
    subkey = "Software\Dummy\DummyApp\1.0"  ' key name
    x = RegOpenKeyEx(HKEY_CURRENT_USER, subkey, 0, KEY_READ, hregkey)
    If x <> 0 Then  ' error opening key -- abort!
      Debug.Print "Could not open registry key."
      Exit Sub
    End If
    ' We want to read dword and vbstring from the registry key hregkey
    ' Set dword to the contents of "number"
    x = RegQueryValueEx(hregkey, "number", 0, datatype, dword, 4)
    ' datatype should equal REG_DWORD
    If x <> 0 Then Goto QueryError  ' abort to error handler if an error occured
    ' Set vbstring to the contents of "string", using the mandatory alternate declare
    x = RegQueryValueExString(hregkey, "string", 0, datatype, vbstring, 100)
    ' datatype should equal REG_SZ
    If x <> 0 Then Goto QueryError  ' again, abort if an error occured
    x = RegCloseKey(hregkey)
    Debug.Print dword; vbstring  ' display data read
    Exit Sub  ' quit normal execution
    QueryError:
    Debug.Print "Error reading registry data."
    x = CloseKey(hregkey)  ' closing key frees up resources
    Exit Sub  ' abort

Related Call: RegSetValueEx
Category: Registry
Back to the index.