Chri.s
Chri.s

Reputation: 1456

VBA - Cant access object inside collection directly; only through "for each" loop

I'm exploring the use of getting computer information through VBA and upon that I tried to access a specific item inside the object collection. However, when trying to do so I'm receiving the following error which is absolutely driving me nuts:

Run-time error '-2147217407 (8001001)': 
Generic failure`

The code I'm using is as follows:

Sub ProcessorInfo()
    Dim cimv2, PInfo, PItem, var
    Dim PubStrComputer As String
    PubStrComputer = "."
    Set cimv2 = GetObject("winmgmts:\\" & PubStrComputer & "\root\cimv2")
    Set PInfo = cimv2.ExecQuery("Select * From Win32_Processor")

    For Each PItem In PInfo
        MsgBox ("Processor: " & PItem.Name & vbCrLf & "Id: " & PItem.ProcessorId)
    Next PItem

    ' Error occurs here: trying to access value directly:
    Debug.Print PInfo(1).Properties_(1).Value

End Sub

I've tried ALOT of possible combinations to access the variable/value but always receiving the error mentioned above.

An example that do not work is:

PInfo(1)("Properties_")(1).value

Question: How do I get the value of a specific variable directly in this setup?

You can find the visual setup of the collection below:

enter image description here

Upvotes: 3

Views: 187

Answers (1)

CLR
CLR

Reputation: 12289

Yep, that's odd.

I'd probably just tackle it this way:

target_processor = 1
target_property = 1
this_processor = 0
this_property = 0

For Each PItem In PInfo
    this_processor = this_processor + 1
    For Each prop In PItem.Properties_
        this_property = this_property + 1
        If this_property = target_property And this_processor = target_processor Then
            Debug.Print "Processor: " & PItem.Name & vbCrLf & "Id: " & " " & PItem.ProcessorId & vbCrLf & prop.Name & ": " & prop.Value
        End If
    Next prop
Next PItem

You could extend this method to copy the entire query result into an array if you intend to use multiple replies.

Upvotes: 1

Related Questions