我對VBA Excel 2013有點熟悉。現在我的問題是,我需要總結特定字符串可用的值。 我需要在列內計算只有查找爲真的值。 我的表如下所示:一個數組中的Calculatin
9 | AD,DCO,PD
5 | AD
5 | PD
15 | PD
所以對於AD的總和是14或DCO將是9或PD將是29的,因此結果表都看起來像這樣:
AD | DCO | PD
—–—–—–—–—–––—–
14 | 9 | 29
燦有人幫助我?
我對VBA Excel 2013有點熟悉。現在我的問題是,我需要總結特定字符串可用的值。 我需要在列內計算只有查找爲真的值。 我的表如下所示:一個數組中的Calculatin
9 | AD,DCO,PD
5 | AD
5 | PD
15 | PD
所以對於AD的總和是14或DCO將是9或PD將是29的,因此結果表都看起來像這樣:
AD | DCO | PD
—–—–—–—–—–––—–
14 | 9 | 29
燦有人幫助我?
問題已解決,但您有任何建議來加快代碼?
Sub Calculate()
Dim Dict As Object
Dim i As Long
Dim e As Long
Set Dict = CreateObject("Scripting.Dictionary")
Dim b, m As Long
Dim a As Long
Dim c As Variant
Dim j As Long
Dim sum_Dict As Variant
Dim column_Dict As Variant
i = 1
e = 16
a = i
a = a - 2
For i = i To e
For Each sum_Dict In Range("A" & i & ":" & "A" & e) 'Spalte V = Price
If sum_Dict = "" Then
i = i + 1
Else
For Each c In Range("B" & i & ":F" & i) 'All Columns from B til F
' iterating over the array
For j = LBound(column_Dict) To UBound(column_Dict)
' assigning the separated values to columns
b = CDbl(sum_Dict) 'convert to double
c = CStr(c) 'convert to string
If Dict.Exists(c) Then 'check if key exists
Dict.Item(c) = Dict.Item(c) + b 'if key exists sum the items
Else 'if the key does not exist create it
Dict.Add Key:=c, Item:=b
End If
Next j
Next c
i = i + 1
'extract keys into variant array
'Debug.Print "Array of Keys and items"
For m = 0 To Dict.Count - 1
'Debug.Print Dict.Keys()(m), Dict.Items()(m)
Next m
'Debug.Print Dict.Count & " Items in Dictionary"
End If
Next sum_Dict
Next
'-- output to sheet using first 1D Array
Range("H" & a + 2).Resize(1, _
UBound(Application.Transpose(Dict.Keys()))) = Dict.Keys()
'-- output to sheet using dictionary
Range("H" & a + 3).Resize(1, _
UBound(Application.Transpose(Dict.Items()))) = Dict.Items()
Dict.RemoveAll ' empty dictionary
末次
忘記VBA。 Sumproduct完美地解決了這個問題。
我假設你的逗號分隔單元格,所以列A有數字,然後列B-D有字母。如果他們不這樣做,你可以在Excel中始終使用Text to Columns
函數(查看Data
選項卡)以實現這一目標。
把下面的函數,你wnat答案(比如,B10):
=SUMPRODUCT(($A$1:$A$4) * ($B$1:$D$4 = $A$10))
然後,您可以鍵入細胞A10
代碼字母,它會總結A列,其中列BD包含文本。
如果你想顯示的所有文字選項,你可以讓他們(說A10 = AD
,A11 = DCO
,A12 = PD
),然後在B10把同樣的公式以上,但在號碼前刪除$(這樣的列表它讀取$A10
)。然後,您可以將其拖下來,並將它與A10-A13中的每個值相加,並將結果顯示在B10 - B13中。
如果我已經正確解釋示例數據到一個僞表然後天然SUMIF
功能將在列A中使用針對列B.實施例D2通配符標準(如下面的圖)將是=SUMIF($B$1:$B$4,"*"&D$1&"*",$A$1:$A$4)
有條件求和數。
填充或複製權是必要的。謹慎的是,當標準與其他值非常相似時,通配符可能會產生誤報。您的示例數據並非如此。
可以使用'Scripting.Dictionary'對象。循環遍歷單元格,並將每個結果數組上的逗號:循環中的每個值分開,將第一個元素作爲值,並使用Dictionary的Exists方法檢查每個後續元素 - 「key [s]」。如果不存在,則添加鍵和值,或者如果存在,則增加鍵的值。最後,循環鍵和值以獲得所需的輸出。 – 2014-10-10 06:15:41
好吧 - 現在看來你的「價值」是在一個單獨的專欄中,但基本方法仍然適用。 – 2014-10-10 17:30:12