如何在Excel中的列表中找到兩個數字的所有可能和?
假設這裡是一個數字列表,現在您可以在此列表中找到兩個數字的所有可能總和,如下面的屏幕截圖所示? 在Excel中,沒有內置函數可以解決此任務。 現在,我向您介紹一個VBA代碼來處理它。
Find all possible sums of two numbers in a list with VBA code
Find all possible combinations of two lists with List All Combinations
Find all possible sums of two numbers in a list with VBA code
如果要在列表中查找兩個數字的所有可能和,可以在VBA代碼下面應用。
1。 按 Alt + F11 鍵顯示 Microsoft Visual Basic for Applications 窗口。
2。 點擊 Insert > Module,將以下代碼複製並粘貼到模塊中。
VBA: List all possible sums of two numbers in a list
Sub Combinations()
'UpdatebyExtendoffice20180628
Dim xRgArr
Dim xNum As Long
Dim I, J, K As Long
Dim xTemp As Double
Dim xRg As Range
Dim xRgCount As Long
Dim xDic As New Dictionary
On Error Resume Next
Set xRg = Application.InputBox("Select a list (one column):", "KuTools for Excel", Selection.Address, , , , , 8)
If (xRg Is Nothing) Or (xRg.Count = 1) Then Exit Sub
xRgCount = xRg.Count
K = 1
ReDim xRgArr(1 To xRgCount)
For Each xCell In xRg
xRgArr(K) = xCell.Value
K = K + 1
Next
K = 0
For I = 1 To xRgCount
For J = I + 1 To xRgCount
xTemp = xRgArr(I) + xRgArr(J)
If Not xDic.Exists(xTemp) Then
xDic.Add CDbl(xTemp), CStr(xTemp)
K = K + 1
End If
Next
Next
Range("C1").Resize(xDic.Count, 1) = Application.WorksheetFunction.Transpose(xDic.Keys)
End Sub
3。 點擊 Tools > References,在彈出的對話框中,選中 Microsoft Scripting Runtime 複選框。
4。 點擊 OK 關閉對話框,然後按 F5 要運行代碼,將彈出一個對話框,提醒您選擇一個列表以查找可能的金額。
5。 點擊 OK,則列表C中列出了列表中兩個數字的所有可能總和。
Tip:在代碼字符串Range(“ C1”)。Resize(xDic.Count,1)中,您可以根據需要將C1更改為另一個單元格。
Find all possible combinations of two lists with List All Combinations
如果要查找或列出兩個列表的所有可能組合,如下面的屏幕截圖所示,則 List All Combinations 的效用 Kutools for Excel 可以幫你一個忙。
Excel的Kutools, 與以上 300 方便的功能,使您的工作更加輕鬆。 |
1。 點擊 Kutools > Insert > List All Combinations.
2。 在裡面 List All Combinations 對話框中,單擊選擇按鈕以選擇要合併的第一個列表。
3。 點擊 Add 將列表添加到 Combinations list 部分。
4.重複步驟2和3,將第二個列表添加到 Combinations list.
5。 然後點擊 Ok 選擇要放置組合結果的單元格。
6。 點擊 OK。 所有可能的組合已在單元格中列出。