|
Option Explicit
Private shWords As Worksheet
Private shDataSource As Worksheet
Public Sub wordTotal()
' Total by keywords
Dim dict As Dictionary
Dim rng As Range
Dim arr As Variant
Dim clearsettings As New clsExcelSettings
Dim t
t = Timer
clearsettings.TurnOff
' Create keywords dictionary
Set dict = createLangauageDict
' Read data source
Set rng = createDataSourceArr
arr = rng
' If match then total results
Set dict = createTotalDict(dict, arr)
'Wirte results
Call writeResults(dict)
clearsettings.Restore
MsgBox ("程序运行了" & Format(Timer - t, "0.00" & "秒"))
End Sub
' Create keywords dictionary
Private Function createLangauageDict() As Dictionary
Dim dict As New Dictionary
Dim rg As Range
Dim keyWord As String
Dim i As Long
Dim cCode As clsCode
Set shWords = shTotal
Set rg = shWords.Range("A1").CurrentRegion
For i = 2 To rg.Rows.Count
keyWord = Cells(i, 1)
If dict.Exists(keyWord) = True Then
Set cCode = dict(keyWord)
Else
Set cCode = New clsCode
dict.Add keyWord, cCode
End If
cCode.amount = 0
cCode.Count = 0
Next i
' Return
Set createLangauageDict = dict
End Function
' Read data source
Private Function createDataSourceArr() As Range
Dim rng As Range
Set shDataSource = shData
Set rng = shDataSource.Range("A1").CurrentRegion
' Return
Set createDataSourceArr = rng
End Function
' If match then total results
Private Function createTotalDict(dict, arr) As Dictionary
Dim keyWord As Variant
Dim i As Long
Dim amount As Double
Dim summary As String
Dim cCode As clsCode
'Match
For Each keyWord In dict.Keys
Set cCode = dict(keyWord)
For i = LBound(arr, 1) + 1 To UBound(arr, 1)
amount = Val(arr(i, 2))
summary = arr(i, 1)
' Conditions
If InStr(summary, keyWord) <> 0 And amount <> 0 Then
cCode.amount = cCode.amount + amount
cCode.Count = cCode.Count + 1
End If
Next i
Next
' ' If item equals zero then delete
Dim key As Variant
For Each key In dict.Keys
Set cCode = dict(key)
If cCode.amount = 0 Then dict.Remove (key)
Next
' Return
Set createTotalDict = dict
End Function
' Wirte results
Private Sub writeResults(dict) 'dict代表字典对象
Dim key As Variant
Dim i As Long
Dim cCode As clsCode
shWords.Range("C1").CurrentRegion.Offset(1).ClearContents
' Write
i = 2
For Each key In dict.Keys
Set cCode = dict(key)
shWords.Cells(i, "C") = key
shWords.Cells(i, "D") = cCode.amount
shWords.Cells(i, "E") = cCode.Count
i = i + 1
Next
'Sort
Dim rg As Range
Set rg = shWords.Range("C1:E" & 65536)
rg.Sort Key1:=shWords.Range("D1"), Order1:=xlDescending, Header:=xlYes
End Sub
|
|