gpt4 book ai didi

excel - 创建一个集合作为字典的值

转载 作者:行者123 更新时间:2023-12-04 22:26:59 25 4
gpt4 key购买 nike

我正在尝试创建一个包含集合作为其值的字典,因为我有多个变量,它们具有不同数量的属性。我希望避免创建一个类。

Sub test()

Set dict = CreateDict()

Debug.Print "Done!"
End Sub

Private Function CreateDict() As Scripting.Dictionary
Set dict = New Scripting.Dictionary
dict.CompareMode = vbTextCompare


Set wb = CreateObject("excel.Application").Workbooks.Open("S:\filename.xlsx")
Set wks = wb.Worksheets(1)

Row = 2
Do While IsEmpty(wks.Cells(Row, 1)) = False

key = wks.Cells(Row, 1)
value = wks.Cells(Row, 3)

'Debug.Print key, value

If dict.Exists(key) Then
dict(key).Add value
Else
Dim col As New Collection
col.Add value
dict.Add key, col
End If

Row = Row + 1
Loop

Workbooks("filename.xlsx").Close savechanges:=False

Dim key1 As Variant
For Each key1 In dict.Keys
Debug.Print key1, dict(key1)(1)
Next key1

Set CreateDict = dict
End Function

我的键添加正确,但是当我尝试访问我的集合的第一个值时,它是空的,即使我打印 value在它不为空之前。

我希望我一周前刚开始使用 VBA 时没有犯愚蠢的错误。任何帮助将不胜感激,如果有更简单的方法,或者如果有现有的方法可以做到这一点,我很高兴知道。

提前致谢

编辑:

不幸的是,对于任何想知道这不起作用的人,因为 VBA 不会每次都创建新集合 Dim col As New Collection被申请;被应用。相反,所有值都只是添加到一个集合 col .但是我找到了一个解决方法,因为动态变量名在 VBA 中是不可能的,根据这篇文章 Set variable name with string variable in VBA .

但是,我刚刚创建了一个创建并返回集合的函数。我的代码现在如下所示:
Sub test()

Set dict = CreateDict()

Debug.Print "Done!"
End Sub

Private Function CreateDict() As Scripting.Dictionary
Set dict = New Scripting.Dictionary
dict.CompareMode = vbTextCompare


Set wb = CreateObject("excel.Application").Workbooks.Open("S:\filename.xlsx")
Set wks = wb.Worksheets(1)

Row = 2
Do While IsEmpty(wks.Cells(Row, 1)) = False

key = wks.Cells(Row, 1)
value = wks.Cells(Row, 3)

'Debug.Print key, value

If dict.Exists(key) Then
dict(key).Add value
Else
dict.Add key, CreateCollection()
dict(key).Add value
End If

Row = Row + 1
Loop

Workbooks("filename.xlsx").Close savechanges:=False

Set CreateDict = dict
End Function

Private Function CreateCollection() As Collection
Dim col As New Collection
Set CreateCollection = col
End Function

最佳答案

而不是 dict(key1)(0) ,展开代码如下:

Dim c as Collection
Set c = dict(key1)
Debug.Print c(1) ' or c.item(1)

两个问题:
  • 集合的索引从 1†
  • 开始
  • 如果没有类型信息,VBA 有时无法正确解析链式方法调用。

  • https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/item-method-visual-basic-for-applications

    关于excel - 创建一个集合作为字典的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56950893/

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