我有2个qns应该在VBA代码中执行。 1.我想计算一个特定字符串在一列中超过40个唯一值重复的总次数。这可以实现。
例如,像Apple,香蕉,葡萄这样的独特值(40个以上的唯一值)在一列中重复,我希望像这样计算单个字符串。
Apple- 30 times repeated
banana- 4 times repeated.
例如,计算苹果,只要成本超过40 数葡萄,只要成本高于40
可以帮助解决这个问题,如何在VBA代码中实现这一点。
答案 0 :(得分:0)
以下代码将A列中的所有字符串添加到集合结构中,在计算每个唯一值时对其进行排序,并将每个唯一值和相应的和存储在字典结构中。然后将结果打印到立即窗口。希望这会有所帮助。
Sub main()
'variables
Dim colCollection As New Collection
Dim x, q As Variant
Dim cellValue As String
Dim j, i, count As Integer
Dim numbers As New Scripting.Dictionary 'NOTE: add microsoft scripting Runtime Ref
x = 1 'collections start at 1
While Worksheets("Sheet1").Cells(x, "A").Value <> "" 'while cell is not empty
cellValue = Worksheets("Sheet1").Cells(x, "A").Value 'store string value from cell
colCollection.Add (cellValue) ' add entry from cell to collection
x = x + 1 'increment
Wend
'Sort collection (bubbble sort) and record number of each unique item
For i = colCollection.count To 2 Step -1 'count down from collection
For j = 1 To i - 1
'bubble up item
If colCollection(j) > colCollection(j + 1) Then
colCollection.Add colCollection(j), After:=j + 1
colCollection.Remove j
End If
Next j
'finding count of unique item
If i <> colCollection.count Then 'if not at last item (can't compare 2 items when only given 1)
If i = 2 Then 'if at end
numbers.Add colCollection(i), count + 3 'add sum to dictionary with corresponding key value
Else
If StrComp(colCollection(i + 1), colCollection(i), 1) = 0 Then 'if same string
count = count + 1 'increment count
Else
numbers.Add colCollection(i + 1), count + 1 'add sum to dictionary with corresponding key value
count = 0 'reset count
End If
End If
End If
Next i
'loop through dictionary
For Each q In numbers.Keys
Debug.Print q & "- " & numbers.Item(q); " times repeated."
Next
End Sub