对于每个行业(IT,非必需消费品,金融等),我想添加投资百分比并返回结果总和值。例如,IT应返回7%(1 + 2 + 4),医疗保健应返回24%(7 + 8 + 9)。
这是我到目前为止:
Dim sector_array As Variant
Dim sector As Variant
Dim ocell As Range
Dim rng As Range
sector_array = Array("Information Technology", "Financials", "Consumer
Discretionary", "Energy", "Materials", "Consumer Staples", "Health Care",
"Industrials", "Utilities", "Telecommunication Services", "Real Estate")
For Each sector In sector_array
For Each ocell In Range("C:C")
If ocell.Value = sector Then
If rng Is Nothing Then
Set rng = ocell.EntireRow
Else
Set rng = Union(rng, ocell.EntireRow)
End If
End If
Next ocell
If Not rng Is Nothing Then
rng.Select
End If
Next sector
我该怎么做到这一点?
我会做一个SUMIF公式,指定F列中的每个类别。
使用字典。键是扇区,并且是百分比的值。如果存在密钥,则将百分比添加到现有值。
Option Explicit
Public Sub test()
Dim lastRow As Long, dict As Object, i As Long, key As Variant
With ActiveSheet
Dim dataArr()
dataArr = .Range("C2:E" & .Cells(.Rows.Count, "C").End(xlUp).Row).Value
End With
Set dict = CreateObject("Scripting.Dictionary")
For i = LBound(dataArr, 1) To UBound(dataArr, 1)
If Not dict.exists(dataArr(i, 1)) Then
dict.Add dataArr(i, 1), dataArr(i, 3)
Else
dict(dataArr(i, 1)) = dict(dataArr(i, 1)) + dataArr(i, 3)
End If
Next i
For Each key In dict.keys
Debug.Print key & " : " & dict(key)
Next key
End Sub
立即窗口中的结果(Ctrl + G)