メインコンテンツへスキップ

Excelで特定の合計に等しいすべての組み合わせを見つける方法は?

予算編成、計画、データ分析の目的を問わず、リスト内で合計が特定の合計になる数値の可能な組み合わせをすべて見つけることは、多くの Excel ユーザーが遭遇する可能性のある課題です。

この例では、数値のリストがあり、目的は、このリストのどの組み合わせの合計が 480 になるかを特定することです。提供されたスクリーンショットは、300+120 のような組み合わせを含め、この合計を達成する組み合わせのグループが 60 つあることを示しています。 +250、120+60+50+XNUMXなど。この記事では、Excel で指定された値を合計するリスト内の数値の特定の組み合わせを特定するさまざまな方法を検討します。

ソルバー関数を使用して、指定された合計に等しい数値の組み合わせを見つけます

指定された合計に等しい数値のすべての組み合わせを取得します

VBAコードを使用して、合計が範囲内にある数値のすべての組み合わせを取得します


ソルバー関数を使用して、指定された合計に等しいセルの組み合わせを検索します。

Excel に飛び込み、合計すると特定の数値になるセルの組み合わせを見つけるのは困難に思えるかもしれませんが、ソルバー アドインを使用すると簡単になります。ソルバーをセットアップし、セルの適切な組み合わせを見つけて、複雑に見えるタスクを簡単かつ実行可能にするための簡単な手順を説明します。

ステップ 1: ソルバー アドインを有効にする

  1. にアクセスしてください File > オプション、で Excelのオプション ダイアログボックスで、をクリックします。 アドイン 左側のペインで、 をクリックします。 Go ボタン。 スクリーンショットを参照してください:
  2. そうして アドイン ダイアログが表示されるので確認してください ソルバーアドイン オプションをクリックして OK このアドインを正常にインストールするには。

ステップ2:数式を入力します

Solver アドインをアクティブ化した後、次の数式をセル B11 に入力する必要があります。

=SUMPRODUCT(B2:B10,A2:A10)
Note:この式では: B2:B10 番号リストの横にある空白セルの列であり、 A2:A10 は使用する番号リストです。

ステップ 3: ソルバーを構成して実行し、結果を取得する

  1. 且つ > ソルバーパラメーター ダイアログボックスのダイアログで、次の操作を行ってください。
    • (1.)クリック セルを選択するボタン B11 数式がどこにあるか 目標を設定する セクション;
    • (2.)次に セクション、選択 の価値、および目標値を入力します 480 必要に応じて;
    • (3.) 変数変換による セクションをクリックしてください セル範囲を選択するボタン B2:B10 どこに対応する番号をマークします。
    • (4.)次に、をクリックします Add
  2. 次に、 制約を追加 ダイアログボックスが表示されるので、クリックします セル範囲を選択するボタン B2:B10、および選択 ビン ドロップダウンリストから。最後にクリックしてください OK ボタン。 スクリーンショットを参照してください:
  3. ソルバーパラメーター ダイアログで、 解決する ボタン、数分後、 ソルバーの結果 ダイアログ ボックスが表示され、指定された合計 480 に等しいセルの組み合わせが列 B で 1 としてマークされていることがわかります。 ソルバーの結果 ダイアログで、選択してください ソルバーソリューションを維持 オプションをクリックして OK ダイアログを終了します。 スクリーンショットを参照してください:
Note注: ただし、この方法には制限があります。有効な組み合わせが複数存在する場合でも、指定された合計に達するセルの組み合わせは 1 つしか識別できません。

指定された合計に等しい数値のすべての組み合わせを取得します

Excel のさらに奥深い機能を探索すると、特定の合計に一致するすべての数値の組み合わせを見つけることができます。これは、思っているよりも簡単です。このセクションでは、指定された合計に等しい数値のすべての組み合わせを見つけるための 2 つの方法を説明します。

ユーザー定義関数を使用して、指定された合計に等しい数値のすべての組み合わせを取得します

集合的に特定の値に達する、特定のセットから考えられるすべての数値の組み合わせを明らかにするには、以下に概説するカスタム関数が効果的なツールとして機能します。

手順 1: VBA モジュール エディターを開いてコードをコピーする

  1. 押したまま Alt + F11 Excelでキーを押すと、 アプリケーション向け Microsoft Visual Basic 窓。
  2. インセット > モジュール、モジュールウィンドウに次のコードを貼り付けます。
    VBA コード: 指定された合計に等しい数値のすべての組み合わせを取得します
    Public Function MakeupANumber(xNumbers As Range, xCount As Long)
    'updateby Extendoffice
        Dim arrNumbers() As Long
        Dim arrRes() As String
        Dim ArrTemp() As Long
        Dim xIndex As Long
        Dim rg As Range
    
        MakeupANumber = ""
        
        If xNumbers.CountLarge = 0 Then Exit Function
        ReDim arrNumbers(xNumbers.CountLarge - 1)
        
        xIndex = 0
        For Each rg In xNumbers
            If IsNumeric(rg.Value) Then
                arrNumbers(xIndex) = CLng(rg.Value)
                xIndex = xIndex + 1
            End If
        Next rg
        If xIndex = 0 Then Exit Function
        
        ReDim Preserve arrNumbers(0 To xIndex - 1)
        ReDim arrRes(0)
        
        Call Combinations(arrNumbers, xCount, ArrTemp(), arrRes())
        ReDim Preserve arrRes(0 To UBound(arrRes) - 1)
        MakeupANumber = arrRes
    End Function
    
    Private Sub Combinations(Numbers() As Long, Count As Long, ArrTemp() As Long, ByRef arrRes() As String)
    
        Dim currentSum As Long, i As Long, j As Long, k As Long, num As Long, indRes As Long
        Dim remainingNumbers() As Long, newCombination() As Long
        
        currentSum = 0
        If (Not Not ArrTemp) <> 0 Then
            For i = LBound(ArrTemp) To UBound(ArrTemp)
                currentSum = currentSum + ArrTemp(i)
            Next i
        End If
     
        If currentSum = Count Then
            indRes = UBound(arrRes)
            ReDim Preserve arrRes(0 To indRes + 1)
            
            arrRes(indRes) = ArrTemp(0)
            For i = LBound(ArrTemp) + 1 To UBound(ArrTemp)
                arrRes(indRes) = arrRes(indRes) & "," & ArrTemp(i)
            Next i
        End If
        
        If currentSum > Count Then Exit Sub
        If (Not Not Numbers) = 0 Then Exit Sub
        
        For i = 0 To UBound(Numbers)
            Erase remainingNumbers()
            num = Numbers(i)
            For j = i + 1 To UBound(Numbers)
                If (Not Not remainingNumbers) <> 0 Then
                    ReDim Preserve remainingNumbers(0 To UBound(remainingNumbers) + 1)
                Else
                    ReDim Preserve remainingNumbers(0 To 0)
                End If
                remainingNumbers(UBound(remainingNumbers)) = Numbers(j)
                
            Next j
            Erase newCombination()
    
            If (Not Not ArrTemp) <> 0 Then
                For k = 0 To UBound(ArrTemp)
                    If (Not Not newCombination) <> 0 Then
                        ReDim Preserve newCombination(0 To UBound(newCombination) + 1)
                    Else
                        ReDim Preserve newCombination(0 To 0)
                    End If
                    newCombination(UBound(newCombination)) = ArrTemp(k)
    
                Next k
            End If
            
            If (Not Not newCombination) <> 0 Then
                ReDim Preserve newCombination(0 To UBound(newCombination) + 1)
            Else
                ReDim Preserve newCombination(0 To 0)
            End If
            
            newCombination(UBound(newCombination)) = num
    
            Combinations remainingNumbers, Count, newCombination, arrRes
        Next i
    
    End Sub
    

ステップ 2: カスタム数式を入力して結果を取得します

コードを貼り付けた後、コード ウィンドウを閉じてワークシートに戻ります。空のセルに次の数式を入力して結果を出力し、 を押します。 入力します キーを押してすべての組み合わせを取得します。スクリーンショットを参照してください:

=MakeupANumber(A2:A10,B2)
Note:この式では: A2:A10 は数値リストであり、 B2 取得したい合計金額です。

先端: 組み合わせ結果を縦に列にリストしたい場合は、次の式を適用してください。
=TRANSPOSE(MakeupANumber(A2:A10,B2))
この方法の限界:
  • このカスタム関数は Excel 365 と 2021 でのみ機能します。
  • この方法は正の数にのみ有効です。小数値は自動的に最も近い整数に丸められ、負の数値を指定するとエラーが発生します。

強力な機能を使用して、指定された合計に等しい数値のすべての組み合わせを取得します

前述の関数の制限を考慮して、迅速かつ包括的なソリューションをお勧めします。Kutools for Excel の Make up a Number 機能は、Excel のあらゆるバージョンと互換性があります。この代替方法では、正の数、小数、負の数を効果的に処理できます。この機能を使用すると、指定された合計に等しいすべての組み合わせをすばやく取得できます。

ヒント: これを適用する 数字を作る 機能を使用するには、まずダウンロードする必要があります Kutools for Excel、次に機能をすばやく簡単に適用します。
  1. クツール > コンテンツ > 数字を作る、スクリーンショットを参照してください:
  2. そして、 数字を作る ダイアログボックスをクリックしてください ボタンをクリックして、使用する番号リストをから選択します。 情報元、次に合計数をに入力します 合計 テキストボックス。 最後に、をクリックします OK ボタン、スクリーンショットを参照してください:
  3. 次に、プロンプト ボックスが表示され、結果を検索するセルを選択するよう通知され、クリックします。 OK、スクリーンショットを参照してください:
  4. そして現在、以下のスクリーンショットのように、指定された番号に等しいすべての組み合わせが表示されています。
Note: この機能を適用するには、 Kutools for Excelをダウンロードしてインストールします 最初。

VBAコードを使用して、合計が範囲内にある数値のすべての組み合わせを取得します

場合によっては、合計が特定の範囲内の合計になる、考えられる数値の組み合わせをすべて特定する必要がある状況に陥ることがあります。たとえば、合計が 470 ~ 480 の間に収まる、考えられるすべての数値グループを見つけようとしているとします。

Excel では、合計が特定の範囲内の値になる、考えられる数値の組み合わせをすべて見つけることは、魅力的で非常に実用的な課題となります。このセクションでは、このタスクを解決するための VBA コードを紹介します。

手順 1: VBA モジュール エディターを開いてコードをコピーする

  1. 押したまま Alt + F11 Excelでキーを押すと、 アプリケーション向け Microsoft Visual Basic 窓。
  2. インセット > モジュール、モジュールウィンドウに次のコードを貼り付けます。
    VBA コード: 合計が特定の範囲になる数値のすべての組み合わせを取得します
    Sub Getall_combinations()
    'Updateby Extendoffice
        Dim xNumbers As Variant
        Dim Output As Collection
        Dim rngSelection As Range
        Dim OutputCell As Range
        Dim LowLimit As Long, HiLimit As Long
        Dim i As Long, j As Long
        Dim TotalCombinations As Long
        Dim CombTotal As Double
        Set Output = New Collection
        On Error Resume Next
        Set rngSelection = Application.InputBox("Select the range of numbers:", "Kutools for Excel", Type:=8)
        If rngSelection Is Nothing Then
            MsgBox "No range selected. Exiting macro.", vbInformation, "Kutools for Excel"
            Exit Sub
        End If
        On Error GoTo 0
        xNumbers = rngSelection.Value
        LowLimit = Application.InputBox("Select or enter the low limit number:", "Kutools for Excel", Type:=1)
        HiLimit = Application.InputBox("Select or enter the high limit number:", "Kutools for Excel", Type:=1)
        On Error Resume Next
        Set OutputCell = Application.InputBox("Select the first cell for output:", "Kutools for Excel", Type:=8)
        If OutputCell Is Nothing Then
            MsgBox "No output cell selected. Exiting macro.", vbInformation, "Kutools for Excel"
            Exit Sub
        End If
        On Error GoTo 0
        TotalCombinations = 2 ^ (UBound(xNumbers, 1) * UBound(xNumbers, 2))
        For i = 1 To TotalCombinations - 1
            Dim tempArr() As Double
            ReDim tempArr(1 To UBound(xNumbers, 1) * UBound(xNumbers, 2))
            CombTotal = 0
            Dim k As Long: k = 0
            
            For j = 1 To UBound(xNumbers, 1)
                If i And (2 ^ (j - 1)) Then
                    k = k + 1
                    tempArr(k) = xNumbers(j, 1)
                    CombTotal = CombTotal + xNumbers(j, 1)
                End If
            Next j
            If CombTotal >= LowLimit And CombTotal <= HiLimit Then
                ReDim Preserve tempArr(1 To k)
                Output.Add tempArr
            End If
        Next i
        Dim rowOffset As Long
        rowOffset = 0
        Dim item As Variant
        For Each item In Output
            For j = 1 To UBound(item)
                OutputCell.Offset(rowOffset, j - 1).Value = item(j)
            Next j
            rowOffset = rowOffset + 1
        Next item
    End Sub
    
    
    

ステップ 2: コードを実行する

  1. コードを貼り付けたら、を押します F5 キーを押してこのコードを実行し、最初に表示されるダイアログで、使用する数値の範囲を選択し、 OK。 スクリーンショットを参照してください:
  2. 2 番目のプロンプト ボックスで、下限値を選択または入力し、[ OK。 スクリーンショットを参照してください:
  3. 3 番目のプロンプト ボックスで、上限の数値を選択または入力し、[ OK。 スクリーンショットを参照してください:
  4. 最後のプロンプト ボックスで、結果の出力が開始される出力セルを選択します。次にクリックします OK。 スクリーンショットを参照してください:

結果

これで、条件を満たす各組み合わせが、選択した出力セルから始まるワークシートの連続した行にリストされます。

Excel では、合計が特定の合計になる数値のグループを見つける方法がいくつか用意されています。方法ごとに動作が異なるため、Excel にどれだけ慣れているか、プロジェクトに必要なものに基づいて方法を選択できます。 Excel のヒントやテクニックをさらに詳しく知りたい場合は、当社の Web サイトで何千ものチュートリアルをご覧ください。 ここをクリックしてアクセスしてください。 読んでいただきありがとうございます。今後さらに役立つ情報を提供できることを楽しみにしています。


関連記事:

  • 可能なすべての組み合わせをリストまたは生成する
  • たとえば、次のXNUMX列のデータがあり、左のスクリーンショットに示すように、XNUMXつの値のリストに基づいて、考えられるすべての組み合わせのリストを生成したいとします。 値が少ない場合はすべての組み合わせをXNUMXつずつ一覧表示できますが、可能な組み合わせを一覧表示する必要がある複数の値を持つ列が複数ある場合は、Excelでこの問題に対処するのに役立つ簡単なトリックをいくつか紹介します。 。
  • 考えられるすべての 4 桁の組み合わせのリストを生成する
  • 場合によっては、4から0までの可能な9桁の組み合わせすべてのリストを生成する必要があります。これは、0000、0001、0002…9999のリストを生成することを意味します。 Excelでリストタスクをすばやく解決するために、いくつかのトリックを紹介します。
Comments (51)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
hola esta muy interesante la demostración del código para excel, pero si deseo que me combine números, con cierta cantidad de números por combinación, por ejemplo 4 números por combinación, y solo me arroje eso, para optimizar la memoria del procesador:
1,2,3,4
2,3,4,5
5,2,6,8

en este caso como sería el código
This comment was minimized by the moderator on the site
Hola muy interesante la explicación, me sirvió bastante, pero deseo consultar como serpia el código si deseo que me de las combinaciones de 6 dígitos, o 5 digitos, según corresponda
This comment was minimized by the moderator on the site
Hi everyone,

I'm trying to find a way to to find all possible combinations of workershifts for a specific amount of workhours within a specific amount of working days.

Both, solver and Kutools basically work, but:

Solver only ever displays one combination not all of them (which is what I would need).

Kutools on the other hand only uses each value once, for example I know there are solutions with say 3 7-hour shifts but it won't pick the shift more than once.

Thanks in advance for any responses!

Hope I'm not threadnecroing too hard here.
This comment was minimized by the moderator on the site
Hello, simsok,
Sorry, I can't understand you clearly.
Could you give your problem more detailed, or can you insert a screenshot of your problem here?
Thank you!
This comment was minimized by the moderator on the site
Thank you so much!!! The solver add-in worked for me!
This comment was minimized by the moderator on the site
How to get list of cell names that add to a given no.
This comment was minimized by the moderator on the site
Hello, Ranka,
I'm sorry, at present, there is no good way for getting the cells that add to a given number.
Thank you!
This comment was minimized by the moderator on the site
ExtendOffice - How To Find All Combinations That Equal A Given Sum In Excel

In this example, I would like to run 100 rows instead of the 8 in your example. When I try to create more rows the formula stops working. I started over with a fresh sheet and I still can not get the formula to work.

Running windows 10
Excel 2207
Office 365
This comment was minimized by the moderator on the site
Hello, Shaw

Unfortunately, the formula in this article has a limit of 20 values, if there are more than 20 numbers, the result will not come out. In this case, I will recommend the Make Up A Number feature of Kutools for Excel, with it, you can find all combinations from the list of numbers. If you have a lot of numbers and many combination results, it will take much time, but you can set the number of combinations to make it faster. See screenshot:
https://www.extendoffice.com/images/stories/comments/comment-skyyang/doc-make-up-number-1.png

You can download this tool from here: https://www.extendoffice.com/download/kutools-for-excel.html
You can try it for free 30 days, please have a try, hope it can help you!
This comment was minimized by the moderator on the site
Hi I have tried doing this with the first method and it just isn't working. I'm unsure what I'm doing wrong as I seem to have followed the instructions exactly. Are there any common errors to watch out for? There is no error showing in the formula itself and all cells are all in the same position as yours are, but it's a list of 48 numbers rather than 8.
This comment was minimized by the moderator on the site
Hello, Angie
If you can't get the result by using the first method, you can view the video at the bottom of this article:
https://www.extendoffice.com/documents/excel/3557-excel-find-all-combinations-that-equal-given-sum.html#demo
Also, you can try our tool-Kutools for Excel's Make up a number feature, it will get all combinations quickly and easily.
Thank you!
This comment was minimized by the moderator on the site
So will any of these work when I have been paid by a client, but with no remit so don’t know which invoices have been paid.
This comment was minimized by the moderator on the site
For the solver add in on excel, can you make it solve for closest to 480 rather than value of 480 (example used above)? I really need some help on how this might work out, thanks in advance

This comment was minimized by the moderator on the site
Could this be adapted to find combinations that sum up to specific range i.e. sum between 450 and 500? Is there a way to set it so that each cell value can be used only in one combination not more?
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations