我是VB的新手,因此在尝试理解事物如何融合时遇到了实际问题。我目前正在尝试使用全局字典来存储标题/列值,以便在运行时可以快速访问它们(因为列数可能会根据内容而变化)。然而,我正在努力使字典工作,它似乎添加值,但后来在代码显示为空,我不知道我做错了什么,并希望任何帮助。
Public dataHeaders As Dictionary
Public Function getCases()
Set dataHeaders = CreateObject("Scripting.Dictionary")
For i = 1 To 100
If IsEmpty(Worksheets("DATA").Cells(1, i)) Then
Exit For
Else
dataHeaders.Add Worksheets("DATA").Cells(1, i), i
End If
Next
For i = 1 To 10
For j = 1 To 750
If Worksheets("Summary").Cells(1, i) = Worksheets("DATA").Cells(dataHeaders("Checker"), j) Then
Worksheets("Summary").Cells(2, i) = Worksheets("Summary").Cells(2, i) + 1
End If
Next
Next
End Function
答案 0 :(得分:0)
我怀疑你的问题是套管问题还是空白问题。要解决此问题,请先使用Trim
和UCase
(或LCase
)规范化您的文字,然后再将其用于字典中。
我测试了以下代码,它输出了我期望的内容..
Sub test()
Dim headers As Dictionary
Dim valueCount As Integer
Dim ws As Worksheet
Dim headerRange As Range
Set ws = Sheet1
Set headers = New Dictionary
'get last column on the right of our header row
valueCount = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
Set headerRange = ws.Cells(1, 1).Resize(1, valueCount)
Dim i As Long
i = 1
For Each cell In headerRange
'Trim and convert to upper when assigning to array.
headers.Add UCase(Trim(cell.Value)), i
i = i + 1
Next cell
For Each Key In headers.Keys
'Note the usage of Trim and UCase
Debug.Print "item: " & Key & " Value : " & headers(UCase(Trim(Key)))
Next Key
End Sub