gpt4 book ai didi

excel - VBA - 无法直接访问集合内的对象;仅通过 "for each"循环

转载 作者:行者123 更新时间:2023-12-04 17:37:06 24 4
gpt4 key购买 nike

我正在探索通过 VBA 获取计算机信息的用途,然后我尝试访问对象集合中的特定项目。但是,当尝试这样做时,我收到以下错误,这绝对让我抓狂:

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

我使用的代码如下:

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

我尝试了很多可能的组合来访问变量/值,但总是收到上述错误。

一个工作的例子是:

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

问题如何在此设置中直接获取特定变量的值?

您可以在下面找到该系列的视觉设置:

enter image description here

最佳答案

是的,这很奇怪。

我可能会这样处理:

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

如果您打算使用多个回复,您可以扩展此方法以将整个查询结果复制到一个数组中。

关于excel - VBA - 无法直接访问集合内的对象;仅通过 "for each"循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56219228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com