首页 > 解决方案 > 从 excel 命名列作为键创建字典

问题描述

我使用的列是从 E 到 BH,但它们是命名的。例如,列 e 被命名为“问题”。我正在尝试从作为主键的单元格值创建一个字典,以查询从 E 到 BH 的范围。

例如,如果我在 E6 上有一个值为“延迟付款”的单元格,我希望能够获取从 E6 到 Bh6 列的范围,然后能够查询其他列,例如 AQ 列上的“摘要”并能够获得AQ6上的相关摘要。

我一直在考虑如何解决这个问题,我认为想要范围的字典是最好的主意,因为 {Key, value} 对数据集,其中命名列可以是键,值将是单元格,我希望能够知道列上的其他值,例如摘要。

下面是我现在正在做的以获得其他值。我在 vba 方面没有太多经验,一周前才开始使用它来工作。

Set cdata = Worksheets("Table")
Dim newRange As Range
dim keyWord as String
KeyWord = "Late payment"
Dim Summary as String


Set rng1 = cdata.Cells.Find(What:=KeyWord, LookAt:=xlWhole)
If Not rng1 Is Nothing Then
    'Sets the range based on cell value
    Set newRange = ccdata.Range("E" & rng1.Row & ":BH" & rng1.Row)
End If

'Gets value and sets column from row number
Summary = cdata.Range("$AQ$" & rng1.Row).Value

标签: excelvba

解决方案


这应该可以满足您的需求。我在数组中包含了标题以保持索引 = 行。

您还必须意识到从范围创建数组会创建一个二维数组,因此它始终是arr(row, 1). 1 不会改变,因为每个范围由 1 列组成。

    Dim dict As Object
    Dim lc As Long
    Dim lr As Long
    Dim i As Long
    Dim arr As Variant
    
    Set dict = CreateObject("Scripting.Dictionary") 'Add Microsoft Scripting Runtime to early-bind
    
    With Sheets("Sheet5") 'Change as needed
        lc = .Cells(1, .Columns.Count).End(xlToLeft).Column
        For i = 5 To lc
            lr = .Cells(.Rows.Count, i).End(xlUp).Row
            arr = .Range(.Cells(1, i), .Cells(lr, i)).Value
            dict.Add .Cells(1, i).Value, arr
        Next i
    End With
    
    'return the value like this: dict("problems")(6, 1)

推荐阅读