VBAからWMI(Windows Management Instrumentation)の StdRegProv クラスを利用して、指定したレジストリキーのすべての値とデータ型を取得する方法について解説します。
前提条件
このコードを実行するには、VBEの「ツール」>「参照設定」から Microsoft WMI Scripting V1.2 Library にチェックを入れるか、または遅延バインディングを使用する必要があります。本記事では参照設定を行う前提のコードを掲載しています。
VBAサンプルコード
以下のコードは、HKEY_CURRENT_USER の指定したレジストリパスにある値の名前とデータを取得し、イミディエイトウィンドウに出力するサンプルです。
Sub レジストリキーのすべての値を列挙()
Const HKEY_CURRENT_USER As Long = &H80000001
Const REG_SZ As Integer = 1
Const REG_EXPAND_SZ As Integer = 2
Const REG_BINARY As Integer = 3
Const REG_DWORD As Integer = 4
Const REG_MULTI_SZ As Integer = 7
Dim strComputer As String
strComputer = "."
Dim oLocator As WbemScripting.SWbemLocator
Dim oService As WbemServices
Dim objRegistry As SWbemObjectEx
Set oLocator = New WbemScripting.SWbemLocator
Set oService = oLocator.ConnectServer(strComputer, "root\default")
Set objRegistry = oService.Get("StdRegProv")
Dim strKeyPath As String
strKeyPath = "Software\Microsoft\Internet Explorer\Main"
Dim arrValueNames As Variant
Dim arrValueTypes As Variant
objRegistry.EnumValues HKEY_CURRENT_USER, strKeyPath, arrValueNames, arrValueTypes
If IsNull(arrValueNames) Then
Exit Sub
End If
Dim i As Long
Dim strText As String
Dim strValueName As String
Dim strValue As String
Dim intValue As Long
Dim arrValues As Variant
For i = LBound(arrValueNames) To UBound(arrValueNames)
strText = arrValueNames(i)
strValueName = arrValueNames(i)
Select Case arrValueTypes(i)
Case REG_SZ
objRegistry.GetStringValue HKEY_CURRENT_USER, strKeyPath, strValueName, strValue
strText = strText & ": " & strValue
Case REG_DWORD
objRegistry.GetDWORDValue HKEY_CURRENT_USER, strKeyPath, strValueName, intValue
strText = strText & ": " & intValue
Case REG_MULTI_SZ
objRegistry.GetMultiStringValue HKEY_CURRENT_USER, strKeyPath, strValueName, arrValues
strText = strText & ": "
If Not IsNull(arrValues) Then
For Each strValue In arrValues
strText = strText & " " & strValue
Next
End If
Case REG_EXPAND_SZ
objRegistry.GetExpandedStringValue HKEY_CURRENT_USER, strKeyPath, strValueName, strValue
strText = strText & ": " & strValue
Case REG_BINARY
objRegistry.GetBinaryValue HKEY_CURRENT_USER, strKeyPath, strValueName, arrValues
strText = strText & ": "
If Not IsNull(arrValues) Then
For Each strValue In arrValues
strText = strText & " " & strValue
Next
End If
End Select
Debug.Print strText
Next
End Sub
使い方と注意点
レジストリを操作・参照する際は、対象のキーや値が存在するかどうか、また適切な権限があるかを確認してください。環境やレジストリの構造によってはエラーが発生する場合がありますので、実務で利用する際はエラーハンドリングを追加してご利用ください。
この記事の更新履歴
この記事は、生成AIを活用した自動レビュー・更新フローにより内容を見直し、必要な修正を反映しています。
2026年9月12日
- 削除リンク切れとなった旧TechNet Script Centerへの参照リンクを削除しました。
- 変更VBAコードの変数の型宣言やインデントを整理し、WordPress上で読みやすいコードブロックへ修正しました。
- 追加WMIのStdRegProvクラスを用いたレジストリ値列挙の前提条件と解説を追加しました。
