메인 컨텐츠로 가기

Excel에서 주어진 합계와 동일한 모든 조합을 찾는 방법은 무엇입니까?

특정 합계를 추가하는 목록 내에서 가능한 모든 숫자 조합을 검색하는 것은 예산 책정, 계획 또는 데이터 분석 목적으로 많은 Excel 사용자가 직면할 수 있는 문제입니다.

이 예에는 숫자 목록이 있으며 목표는 이 목록에서 합이 480이 되는 조합을 식별하는 것입니다. 제공된 스크린샷은 300+120과 같은 조합을 포함하여 이 합을 달성하는 60개의 가능한 조합 그룹이 있음을 보여줍니다. +250, 120+60+50+XNUMX 등. 이 문서에서는 Excel에서 지정된 값을 합산하는 목록 내 특정 숫자 조합을 찾아내는 다양한 방법을 살펴보겠습니다.

Solver 기능을 사용하여 주어진 합계와 동일한 숫자의 조합 찾기

주어진 합계와 동일한 숫자의 모든 조합을 가져옵니다.

VBA 코드를 사용하여 범위에 합계가 있는 모든 숫자 조합 가져오기


Solver 기능을 사용하여 주어진 합계와 동일한 셀 조합 찾기

특정 숫자에 해당하는 셀 조합을 찾기 위해 Excel을 사용하는 것은 어려운 것처럼 보일 수 있지만 Solver 추가 기능을 사용하면 매우 쉽습니다. 솔버를 설정하고 올바른 셀 조합을 찾는 간단한 단계를 안내하여 복잡한 작업처럼 보였던 작업을 간단하고 실행 가능하게 만듭니다.

1단계: 솔버 추가 기능 활성화

  1. 로 이동하십시오 입양 부모로서의 귀하의 적합성을 결정하기 위해 미국 이민국에 > 옵션 ,에 Excel 옵션 대화 상자에서 추가 기능 왼쪽 창에서 다음을 클릭하세요. Go 단추. 스크린 샷보기 :
  2. 그런 다음 추가 기능 대화상자가 나타나면 솔버 애드 인 옵션을 클릭하고 OK 이 추가 기능을 성공적으로 설치합니다.

2 단계 : 수식 입력

해 찾기 추가 기능을 활성화한 후 B11 셀에 다음 수식을 입력해야 합니다.

=SUMPRODUCT(B2:B10,A2:A10)
주의 사항:이 공식에서 : B2 : B10 번호 목록 옆에 있는 빈 셀 열입니다. A2 : A10 사용하는 번호 목록입니다.

3단계: 솔버를 구성하고 실행하여 결과 얻기

  1. Data > 해결사 로 이동합니다 솔버 매개 변수 대화 상자에서 대화 상자에서 다음 작업을 수행하십시오.
    • (1.) 클릭 셀을 선택하는 버튼 B11 귀하의 수식이 어디에 있는지 목표 설정 섹션;
    • (2.) 그런 다음 섹션에서 선택 가치, 목표 값을 입력하십시오. 480 당신이 필요로;
    • (3.) 아래 가변 셀 변경 섹션을 클릭하십시오 셀 범위를 선택하는 버튼 B2 : B10 해당 번호는 어디에 표시됩니다.
    • (4.) 그런 다음 추가 버튼을 클릭합니다.
  2. 그런 다음 제약 추가 대화 상자가 표시되면 클릭하세요. 셀 범위를 선택하는 버튼 B2 : B10, 선택 큰 상자 드롭다운 목록에서 마지막으로 클릭하세요. OK 단추. 스크린 샷보기 :
  3. . 솔버 매개 변수 대화 상자에서 해결 버튼, 몇 분 후 솔버 결과 대화상자가 팝업되며, B열에 주어진 합이 480인 셀의 조합이 1로 표시되는 것을 볼 수 있습니다. 솔버 결과 대화 상자, 선택하십시오 솔버 솔루션 유지 옵션을 클릭하고 OK 대화 상자를 종료합니다. 스크린 샷보기 :
주의 사항: 그러나 이 방법에는 제한이 있습니다. 유효한 조합이 여러 개 존재하더라도 지정된 합계에 해당하는 셀 조합은 하나만 식별할 수 있습니다.

주어진 합계와 동일한 숫자의 모든 조합을 가져옵니다.

Excel의 심층적인 기능을 탐색하면 특정 합계와 일치하는 모든 숫자 조합을 찾을 수 있으며 생각보다 쉽습니다. 이 섹션에서는 주어진 합계와 동일한 숫자의 모든 조합을 찾는 두 가지 방법을 보여줍니다.

사용자 정의 함수를 사용하여 주어진 합계와 동일한 숫자의 모든 조합을 가져옵니다.

주어진 값에 집합적으로 도달하는 특정 세트에서 가능한 모든 숫자 조합을 찾아내려면 아래에 설명된 사용자 정의 기능이 효과적인 도구 역할을 합니다.

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)
주의 사항:이 공식에서 : A2 : A10 번호 목록이고 B2 당신이 얻고 싶은 총합입니다.

: 조합 결과를 세로로 한 열에 나열하려면 다음 수식을 적용하십시오.
=TRANSPOSE(MakeupANumber(A2:A10,B2))
이 방법의 한계:
  • 이 사용자 정의 기능은 Excel 365 및 2021에서만 작동합니다.
  • 이 방법은 양수에만 효과적입니다. 10진수 값은 가장 가까운 정수로 자동 반올림되며 음수는 오류가 발생합니다.

강력한 기능으로 주어진 합계와 동일한 숫자의 모든 조합을 얻으세요

앞서 언급한 기능의 한계를 고려하여 신속하고 포괄적인 솔루션인 Excel용 Kutools의 숫자 구성 기능을 권장합니다. 이 기능은 모든 Excel 버전과 호환됩니다. 이 대안은 양수, 소수 및 음수를 효과적으로 처리할 수 있습니다. 이 기능을 사용하면 주어진 합계와 동일한 모든 조합을 빠르게 얻을 수 있습니다.

방문 꿀팁: 이것을 적용하려면 번호 확인 기능을 먼저 다운로드해야 합니다. Excel 용 Kutools을 클릭 한 다음 기능을 빠르고 쉽게 적용하십시오.
  1. 쿠툴 > 내용 > 번호 확인, 스크린 샷 참조 :
  2. 그런 다음 번호 만들기 대화 상자를 클릭하십시오. 버튼에서 사용할 번호 목록을 선택합니다. 데이터 소스을 클릭 한 다음 총 수를 합계 텍스트 상자. 마지막으로 클릭 OK 버튼, 스크린 샷 참조 :
  3. 그런 다음 결과를 찾을 셀을 선택하라는 메시지 상자가 나타나면 다음을 클릭하십시오. OK, 스크린 샷 참조 :
  4. 이제 해당 숫자와 동일한 모든 조합이 아래 스크린샷과 같이 표시됩니다.
주의 사항: 이 기능을 적용하려면 Excel 용 Kutools 다운로드 및 설치 먼저.

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. 두 번째 프롬프트 상자에서 하한 숫자를 선택하거나 입력하고 OK. 스크린 샷보기 :
  3. 세 번째 프롬프트 상자에서 상한 숫자를 선택하거나 입력하고 OK. 스크린 샷보기 :
  4. 마지막 프롬프트 상자에서 결과 출력이 시작되는 출력 셀을 선택합니다. 그런 다음 클릭 OK. 스크린 샷보기 :

결과

이제 각 적격 조합은 선택한 출력 셀부터 시작하여 워크시트의 연속 행에 나열됩니다.

Excel에서는 특정 합계를 합산하는 숫자 그룹을 찾는 여러 가지 방법을 제공하며, 각 방법은 다르게 작동하므로 Excel에 얼마나 익숙하고 프로젝트에 필요한지에 따라 하나를 선택할 수 있습니다. 더 많은 Excel 팁과 요령을 살펴보고 싶으시다면 저희 웹사이트에서 수천 개의 튜토리얼을 확인하세요. 액세스하려면 여기를 클릭하세요.. 읽어주셔서 감사합니다. 앞으로도 더 유용한 정보를 제공해 드릴 수 있도록 노력하겠습니다!


관련 기사:

  • 가능한 모든 조합을 나열하거나 생성합니다.
  • 다음과 같은 두 개의 데이터 열이 있다고 가정 해 보겠습니다. 이제 왼쪽 스크린 샷에 표시된 두 값 목록을 기반으로 가능한 모든 조합 목록을 생성하려고합니다. 값이 적은 경우 모든 조합을 하나씩 나열 할 수 있지만 가능한 조합을 나열하는 데 필요한 여러 값이있는 열이 여러 개인 경우 Excel에서이 문제를 처리하는 데 도움이되는 몇 가지 빠른 트릭이 있습니다. .
  • 3개 또는 여러 열의 모든 조합 생성
  • 3 개의 데이터 열이 있다고 가정하면 아래 스크린 샷과 같이이 3 개의 열에있는 모든 데이터 조합을 생성하거나 나열하려고합니다. 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