Background: I’m pulling all of the field names from a database into an array – I’ve got this part done without a problem, so I already have an array containing all the fields (allfields()) and I have a count of how many fields there are (numfields).
I am now trying to compile all of the unique combinations that can be made from those various field names. For example, if my three fields are NAME, DESCR, DATE, I would want to return the following:
- NAME, DESCR, DATE
- NAME, DESCR
- NAME, DATE
- DESCR, DATE
- NAME
- DESCR
- DATE
I’ve tried a few different things for this, including multiple nested loops, and modifying the answer here: How to make all possible sum combinations from array elements in VB to fit my needs, but it appears as though I do not have access to the necessary libaries (System or System.Collections.Generic) on my work PC, as it only has VBA.
Does anyone have a bit of VB code kicking around that would fulfill this purpose?
Thanks a lot!
I had a similar requirement some years ago. I do not remember why and I no longer have the code but I do remember the algorithm. For me this was a one-off exercise so I wanted an easy code. I did not care about efficiency.
I will assume one-based arrays because it makes for a marginally easier explanation. Since VBA supports one-based arrays, this should be OK although it is an easy adjustment to zero-based arrays if that is what you want.
AllFields(1 To NumFields) holds the names.
Have a Loop: For Inx = 1 To 2^NumFields – 1
Within the loop consider Inx as a binary number with bits numbered 1 to NumFields. For each N between 1 and NumFields, if bit N is one include AllFields(N) in this combination.
This loop generates the 2^NumFields – 1 combinations:
The only difficulty with VBA is getting the value of Bit N.
Extra section
With everyone having at go at implementing bits of my algorithm, I thought I had better show how I would have done it.
I have filled an array of test data with an nasty set of field names since we have not been told what characters might be in a name.
The subroutine GenerateCombinations does the business. I am a fan of recursion but I do not think my algorithm is complicated enough to justify its use in this case. I return the result in a jagged array which I prefer to concatenation. The output of GenerateCombinations is output to the immediate window to demonstrate its output.
This routine demonstrates GenerateCombinations
GenerateCombinations does the business.