次のようなスプレッドシートがあります:-
Prod No Store 1 $ Store 1 Qty Store 2 Sale Store 2 Qty etc
A 4.00 1 7.50 2
B 0 0 15.00 1
C 4.00 2 -8 -1
D 5.00 1 5.00 1
各部品番号の固有の価格をすべて取得し、各価格の数量を合計する必要があります。例:
Prod No A has 4.00 1 unit and 7.50 2 units
Prod No B has 0.00 0 units and 15.00 1 unit
Prod No C has 4.00 2 units and -8 -1 unit
Prod No D has 5.00 2 units
また、各価格の固有の価格と数量の合計のリストも必要です。
例えば、
4.00 3 units
7.50 2 units
0.00 0 units
-8 -1 unit
15.00 1 unit
5.00 2 units
答え1
まず、データをより水平な形式で保存すると、長期的にはより幸運になると思います。たとえば、
Store Product Qty Sales
Store 1 A 1 4.00
Store 1 B 0 0.00
Store 1 C 2 4.00
Store 1 D 0 0.00
列のペアではなく、単一の列で検索を行う方がはるかに簡単です。
(サイズと規模によっては、Store、Product、Sales のテーブルを別々に持つ Access データベースの方が適している場合もあります)
そうは言っても、現状のままで困っていて、シートに VBA マクロを入れても問題ない場合は、次の方法を試すことができます。
次の内容を含むというクラス モジュールを VBA プロジェクトに追加します
Tuple
。Private szKey As String Private nValue As Double Public Property Get Key() As String Key = szKey End Property Public Property Let Key(newKey As String) szKey = newKey End Property Public Property Get Value() As Double Value = nValue End Property Public Property Let Value(newValue As Double) nValue = newValue End Property
たとえば、次の内容を含む通常のモジュールを
Module 1
プロジェクトに追加します。Public Function Summarize(ByRef rng As Range) As String If rng.Cells.Count Mod 2 = 1 Then Err.Raise 100, "", "Expected range of even cells" Dim coll As New Collection On Error Resume Next Dim flag As Boolean: flag = False Dim prevCel As Range, cel As Range: For Each cel In rng.Cells If flag Then Dim Key As String: Key = "" & prevCel.Value2 coll(Key).Value = coll(Key).Value + cel.Value2 If Err.Number <> 0 Then Err.Clear Dim t1 As New Tuple t1.Key = "" & prevCel.Value2 t1.Value = cel.Value2 coll.Add t1, Key Set t1 = Nothing End If End If Set prevCel = cel flag = Not flag Next cel On Error GoTo 0 Dim t2 As Variant: For Each t2 In coll If Len(Summarize) Then Summarize = Summarize & ", " Summarize = Summarize & Format(t2.Key, "#0.00") & " @ " & t2.Value Next t2 End Function
次に、ワークシートに次のような数式を入力します。
="Product " & $A2 & " has " & Summarize($B2:$I2)
範囲 $B2:$I2 を、すべての可能性のある店舗数をカバーできる十分な広さの範囲に置き換えてください。また、偶数サイズの範囲を使用してください (Sale/Qty の値はペアになっているため)。そうしないと、エラーが発生します
#VALUE
。