Hi Everyone,
I have a power set macro that spits out EVERY combination (non-repeating) of cells I have in Column A. However, I would like to limit the results by having the code reference a number, and only return the results of that number.
Let me explain further. In column A I have Z, F, H, K, N in cells A1:A5. The way the macro works now, it spits out each combination. What I would like to change is to put a number in B1, and have the macro only output those length of combinations. So for example, if I enter 3 in B1, the macro will output:
ZFH
ZFK
ZFN
ZHK
ZHN
ZKN
FHK
FHN
FKN
HKN
Likewise, if I enter 4 in B1, the results would be:
ZFHK
ZFHN
ZFKN
ZHKN
FHKN
Also, as it stands the results are in different cells, is there any way I can get those results to be concatenated within the macro instead of manually doing it? So instead of Z in C2, F in D2, H in E2, K in F2, just have ZFHK in cell C2, ZFHN in cell C3 etc etc
Here's the code I have so far:
Option Explicit
'Power Set
' Set in A1, down. Result in C1, down and accross. Clears C:Z.
Sub PowerSet()
Dim vElements As Variant, vresult As Variant
Dim lRow As Long, i As Long
vElements = Application.Transpose(Range("A1", Range("A1").End(xlDown)))
Columns("C:Z").Clear
lRow = 1
For i = 1 To UBound(vElements)
ReDim vresult(1 To i)
Call CombinationsNP(vElements, i, vresult, lRow, 1, 1)
Next i
End Sub
Sub CombinationsNP(vElements As Variant, p As Long, vresult As Variant, lRow As Long, iElement As Integer, iIndex As Integer)
Dim i As Long
For i = iElement To UBound(vElements)
vresult(iIndex) = vElements(i)
If iIndex = p Then
lRow = lRow + 1
Range("C" & lRow).Resize(, p) = vresult
Else
Call CombinationsNP(vElements, p, vresult, lRow, i + 1, iIndex + 1)
End If
Next i
End Sub
Display More
I am a novice at VBA and would appreciate any help on this. Thank you.
Please see the attached spreadsheet for a better idea.
forum.ozgrid.com/index.php?attachment/59672/