【问题标题】:Building index based on column/category基于列/类别建立索引
【发布时间】:2020-04-09 19:34:22
【问题描述】:

我的数据集有 2 列(实际上是 22 列)如下所示:

filename1 -"123"
filename1 -"xyz"
filename1 -"abc"
filename2 -"123"
filename2 -"Pieter"
etc.

我想根据文件名分块处理它。为此,我需要根据文件名返回一列或多列的垂直范围(按升序排序)。

现在我正在使用字典构建索引。使用一个简单的循环来计算每个唯一值,因此文件名 1、3 - 文件名 2、2 等,然后是第二个循环来读出每个文件名的行数。有了这个,我当然可以计算出我的方式。但是有没有一种不同的,也许更聪明的技术?

Set dictFilenames = CreateObject("scripting.dictionary")

For Each row In Range("A:A")
    file = row.Value
    If Len(file) > 0 Then dictFilenames(file) = dictFilenames(file) + 1
Next row

For i = 0 To dictFilenames.Count - 1
    Debug.Print dictFilenames.Keys()(i), dictFilenames.Items()(i)
Next

【问题讨论】:

  • 这对我来说很好,除非您想存储每个文件名的实际范围,而不仅仅是计数。

标签: excel vba dictionary indexing


【解决方案1】:

字典可以将字典作为项来保存

If Not dictfilenames.exists(file) then

    dictfilenames.add, file, New Scripting.Dictionary  ' or CreateObject("Scripting.Dictionary)

End If

with dictfilenames.Item(file)

    .Add key:=.count, Item:=<value from next column>

End With

通过这种方式,你得到一个字典,其中键是文件名,项目是另一个 scripting.dictionary,顺序键从 0 开始。当然你不需要使用计数来自动索引,你可以使用下一列中值的行号。

例如

    .add key:=<row_number>, Item:=<value from next column>

您现在可以使用

回读嵌套字典中的值
Dim myItem as variant
For each myItem in dictfilenames.item(file) ' myItem is the key in the nested dictionary
    myValue = dictfilenames.item(file).item(myItem)
Next

或者得到一个数组

Dim myArray as variant
myArray = dictfilenames.item(file).Items

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 2021-09-06
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多