我正在下表并借助Excel VBA - Dictionary - 我试图捕捉所有细节 - 1)第一步是在“结果输出”列中搜索 - 如果值为“否” - 那么我们需要用适当的标题读取所有值。 2)因此对于第二条记录 - 即Name = XYZ - 我们需要存储所有细节。根据“主题数量”列 - 我们需要存储所有主题的值及其相应的标记 - 将用于进一步计算并生成“结果”列。
我得到了部分工作 - 就像我能够捕捉细节 - 但无法存储所有主题及其标记的详细信息:
Sr. No. Results Out? Result Name Age No. of Subjects Subject Names Marks
1 Yes Pass ABC 21 3 Maths 10
Science 26
History 34
2 No XYZ 10 2 Maths 24
Science 36
以下是我使用过的部分有效的代码:
Public Sub test_dict()
Dim dict As New Scripting.dictionary
Set dict = New dictionary
sSheetIndex = 1
intTargetRow = 2
Set objUsedRange = Worksheets.Item(3).UsedRange
For Iter = 1 To objUsedRange.Columns.Count
sCellName = objUsedRange.Cells(1, Iter)
sCellValue = objUsedRange.Cells(intTargetRow, Iter)
dict.Item(sCellName) = sCellValue
Next
For i = 0 To dict.Count - 1
s = dict.Items()(i)
Debug.Print dict.Keys()(i) & " " & dict.Items()(i)
Debug.Print s
Next i
End Sub
答案 0 :(得分:1)
解决了以下代码的问题 - 必须使用2个单独的词典:
Public Sub test_dict()
Dim dict As New Scripting.dictionary
Set dict = New dictionary
sSheetIndex = 1
intTargetRow = 2
Set objUsedRange = Worksheets.Item(3).UsedRange
For Iter = 1 To objUsedRange.Columns.Count
sCellName = objUsedRange.Cells(1, Iter)
sCellValue = objUsedRange.Cells(intTargetRow, Iter)
dict.Item(sCellName) = sCellValue
If sCellName = "Subject Names" Then
Call test_dict_2
End If
Next
For i = 0 To dict.Count - 1
s = dict.Items()(i)
Debug.Print dict.Keys()(i) & " " & dict.Items()(i)
Debug.Print s
Next i
End Sub
Public Sub test_dict_2()
Dim dict_2 As New Scripting.dictionary
Set dict_2 = New dictionary
sSheetIndex = 1
intTargetRow = row_counter
Set objUsedRange = Worksheets.Item(3).UsedRange
For Iter = 1 To objUsedRange.Columns.Count
sHeader = objUsedRange.Cells(1, Iter)
sCellValue = objUsedRange.Cells(intTargetRow, Iter)
If sHeader = "No. of Subjects" Then
mv_cnt = sCellValue
End If
If sHeader = "Subject Names" Then
Dim a
a = Iter + mv_cnt
For Iter_2 = Iter To (a - 1)
sHeader = objUsedRange.Cells(1, Iter)
sCellName = objUsedRange.Cells(intTargetRow, Iter)
sCellValue = objUsedRange.Cells(intTargetRow, Iter + 1)
dict_2.Item(sCellName) = sCellValue
intTargetRow = intTargetRow + 1
Next
intTargetRow = row_counter
End If
Next
For i = 0 To dict_2.Count - 1
s = dict_2.Items()(i)
Debug.Print dict_2.Keys()(i) & " " & dict_2.Items()(i)
Debug.Print s
Next i
Set dict_2 = Nothing
End Sub