VBA 词典添加无法读取 Excel sheet 标题,除非我使用 Trim

VBA Dictionary add fails in reading Excel sheet headings unless I use Trim

Function getHeaderRowDict(sht)
    Dim rng As Excel.Range, dict As New Dictionary, i As Long
    Set rng = sht.Range("A1").CurrentRegion.Rows(1)
    For i = 1 To rng.Columns.Count
        dict(Trim(rng.Cells(1, i))) = i
    Next
    Set getHeaderRowDict = dict
End Function

我已经使用这个短代码从 sheet 的 currentRange 的第一行读取单元格,以在以后的代码中用作一种枚举。例如 dict("ID") 到 return 以文本“ID”为标题的列的列号。如果 Trim 函数被遗漏并且它确实没有业务或需要在那里字典returned 所有值都是空的。留下 Trim() 给出了预期的结果。请解释为什么!

来自词典文档:

https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/dictionary-object

The key is used to retrieve an individual item and is usually an integer or a string, but can be anything except an array.

因此您必须小心添加密钥的方式。例如使用一行 headers "Red", "Yellow", "Blue", Green

Sub Tester()
    Dim d, k
    
    'without trim
    Set d = getHeaderRowDict(ActiveSheet)
    For Each k In d
        Debug.Print k, TypeName(k), d(k)
    Next k
'Keys and values look OK, but keys are actually Range objects
'    Red           Range          1
'    Yellow        Range          2
'    Blue          Range          3
'    Green         Range          4
    
    Debug.Print "Red = ", d("Red") '...but not really working

'   Red =
    
    'now using Trim()
    Set d = getHeaderRowDictV2(ActiveSheet)
    For Each k In d
        Debug.Print k, TypeName(k), d(k)
    Next k

'Now we have String-type keys
'   Red           String         1
'   Yellow        String         2
'   Blue          String         3
'   Green         String         4

   Debug.Print "Red = ", d("Red") 'this does work

'  Red =          1

End Sub

Function getHeaderRowDict(sht)
    Dim rng As Excel.Range, dict As New Dictionary, i As Long
    Set rng = sht.Range("A1").CurrentRegion.Rows(1)
    For i = 1 To rng.Columns.Count
        dict(rng.Cells(i)) = i
    Next
    Set getHeaderRowDict = dict
End Function

Function getHeaderRowDictV2(sht)
    Dim rng As Excel.Range, dict As New Dictionary, i As Long
    Set rng = sht.Range("A1").CurrentRegion.Rows(1)
    For i = 1 To rng.Columns.Count
        dict(Trim(rng.Cells(i))) = i '<< added trim, but .Value would also work
    Next
    Set getHeaderRowDictV2 = dict
End Function

...养成始终使用 .Value 而不是依赖默认值 属性 的另一个原因。