[Excel VBA] deal with many conditions inquiries dictionary

Today we share content using VBA code to achieve the function of multi-criteria query.

Data shown in the table below entitled "List" is detailed data.


Again as shown in FIG., The data table named "lookup table" is the data to be queried.

Now we need to name the two conditions and courses of lookup tables, queries related to performance in the schedule.
For VBA, the processing of such a problem is always a fixed routine, determining the relationship condition, the detailed data dictionary cyclic loading, wherein the list of conditions as a key (Key), as a result of the need to query entry (Item ), and finally traversing the query table, according to extract the results.
code show as below:

DicFind Sub ()
Dim D of As Object, ARR, BRR, & I, & J, & K, S $
the Set D = the CreateObject ( "ing.dictionary")
'refers to the dictionary late
' = d.CompareMode the vbTextCompare
'- insensitive
arr = Sheets ( "list"). [A1] .CurrentRegion
'detailed data loaded into the array ARR
the for I = 2 the to the UBound (ARR)
' iterate ARR, the dictionary data is loaded, to prepare for the query
"do the header row, from two lines start traversing
the For J = 2 the To the UBound (ARR, 2)
'header row do not, from the second column traversing
S = ARR (I,. 1) & "@" & ARR (. 1, J)
' name @ courses is query, the dictionary as a key value of
D (S) = ARR (I, J)
'score is the result of the query, the dictionary as Item
the Next
the Next
BRR = Sheets ( "lookup table"). [A1] .CurrentRegion
' query area data is loaded into the array BRR
the For I = 2 the to the UBound (BRR)
S = BRR (I,. 1) & "@"BRR & (I, 2)
'to two conditions combined query string into a condition, subjects name @
The To the UBound J =. 3 for (BRR, 2)
the If d.exists (s) the Then
's, if present in the dictionary variable
BRR (I, J) = D (s)
' s taken from the corresponding entry in the dictionary
Else
BRR (I , J) = ""
'false otherwise empty
End the If
the Next
the Next
Sheets ( "lookup table"). [a1] .CurrentRegion = brr
' brr array back into the query area
MsgBox "query the OK"
the Set d = Nothing
'release Dictionary memory
End Sub


Tips:
1, for dictionary lookup method, in fact, in most cases, there is a problem with many conditions, and to a number of conditions combined into a conditional expression, that is, a single query conditions.
2, note that the code is case sensitive segment, that is "VBA" is not equivalent to "vba", if the need is not case sensitive, canceled the following statement in the code comments.
'd.CompareMode = vbTextCompare' - insensitive
3, a left hand practice questions, VBA code implemented using summing and counting conditions.
As shown below, according to the data on A: column B, and calculating the number of test examinations column D personnel


test and practice files:
https://pan.baidu.com/s/1slv74qp

 

Guess you like

Origin www.cnblogs.com/medik/p/11026494.html