问题
So I already have the list of permutations, but i'd like to convert it to combinations. So i have a single list of names "john" "mike" "tom", and these have already been converted to two columns of permutations "john mike" "john tom" "mike john" "mike tom" "tom john" "tom mike", so how would i go about either deleting the redundant permutations to convert it to combinations, or would it be easier to make a new macro to just generate combinations?
So to be clear, the new list i'm looking for would be "john mike" "john tom" "tom mike"
Here is the macro for permutations given to me yesterday (source).
Sub Permutation()
Dim NameList As Variant, NameVal As Variant, NameVal2 As Variant
Dim Iter As Long
NameList = Sheet3.Range("A1:A108").Value
Iter = 1
For Each NameVal In NameList
For Each NameVal2 In NameList
If NameVal2 <> NameVal Then
Range("C" & Iter).Value = NameVal
Range("D" & Iter).Value = NameVal2
Iter = Iter + 1
End If
Next NameVal2
Next NameVal
End Sub
回答1:
Try this:
Sub NoRepetition()
Dim NameList As Variant, NameVal As Variant, NameVal2 As Variant
Dim Iter As Long, OutputList As Range, NotYet As Boolean
NameList = Range("A1:A5").Value
Iter = 1
For Each NameVal In NameList
For Each NameVal2 In NameList
LRow = Range("C" & Rows.Count).End(xlUp).Row
Set OutputList = Range("C1:C" & LRow)
NotYet = (Application.CountIf(OutputList, NameVal2) = 0)
If NameVal2 <> NameVal And NotYet Then
Range("C" & Iter).Value = NameVal
Range("D" & Iter).Value = NameVal2
Iter = Iter + 1
End If
Next NameVal2
Next NameVal
End Sub
The additional concept is simple: just add a check to see if the name already exists in the first column. If it does, skip that combination. If not, put it in.
Screenshot:
Let us know if this helps.
来源:https://stackoverflow.com/questions/21630030/produce-all-combinations-from-a-list-of-names-in-excel