问题
What I have in Excel document:
A B
Abc 12:34
Def 56:78
Ghi 90:12
Jkl 34:56
...
What I want to achieve with those values:
C D E F
Abc 12:34 Def 56:78
Abc 12:34 Ghi 90:12
Abc 12:34 Jkl 34:56
Def 56:78 Ghi 90:12
Def 56:78 Jkl 34:56
Ghi 90:12 Jkl 34:56
...
Explanation:
Columns A and B can contain any combination of text and numbers (if that is important at all), this example only displays the most common structure. It should create combinations only for rows "on the way down", i. e. "Abc...Def..." is enough, there shouldn't be "Def...Abc...".
There are many examples around, but I am struggling to find a version of such VBA that works with multiple columns and doesn't repeat combinations.
Here is one example that is simple. But, it's for only one column and it also repeats values:
http://www.mrexcel.com/forum/excel-questions/412952-create-list-all-pair-combinations.html#post2046893
Thank you in advance.
回答1:
Given what we discussed in the conversation, here's a solution in VBA:
Sub CreatePermutation()
Dim FirstCell As Integer
Dim SecondCell As Integer
Dim NumRows As Integer
Dim OutputRow As Long
' Get the total number of rows in column A
NumRows = Cells(ActiveSheet.Rows.Count, 1).End(xlUp).Row()
' You want to start outputting in row 1
OutputRow = 1
For FirstCell = 1 To NumRows - 1
For SecondCell = FirstCell + 1 To NumRows
' Put in the data from the first cell into columnc C & D
Cells(OutputRow, 3).Value = Cells(FirstCell, 1).Value
Cells(OutputRow, 4).Value = Cells(FirstCell, 2).Value
' Put in the data from the second cell into column E & F
Cells(OutputRow, 5).Value = Cells(SecondCell, 1).Value
Cells(OutputRow, 6).Value = Cells(SecondCell, 2).Value
' Move to the next row to output
OutputRow = OutputRow + 1
Next SecondCell
Next FirstCell
End Sub
Hope this accomplishes what you're looking to do.
来源:https://stackoverflow.com/questions/22689075/excel-permutations-without-repetition-from-values-in-multiple-columns