Dave, thanks for your sub
For the first part, this was what I meant
'=ABS(D4-D8)<=0.05
The orig sub by JBeaucaire random scrambled the source data within A1:B8
until C4=C8 where
Formula in C4 =SUM(B1:B4)
Formula in C8 =SUM(B5:B8)
to achieve one solution of 2 "equal" groups of 4 items each (1st group in
A1:B4, 2nd group in A5:B8) where their col B sums are equal. The sub inserts
a new col C in the process, hence C4/C8 becomes D4/D8 with the objective
comparison being:
I had wanted to cater for the scenario where it may not be possible to make
it such that the 2 groups sums' are exactly equal, hence an approx solution
(eg a 5% difference or less in the sums) would be acceptable.
Additionally, for the 2nd part of my request, I wanted the sub to continue
to seek beyond just the 1st solution (there could be yet other combinations
which satisfy the criteria), hence the request to leave the source data
intact, and to seek and write the outputs (eg seek/write 3 results sets)
into adjacent areas to the right of the source data in A1:B8
Trust the above clarifies it better.
Dave Peterson said:
I'm not sure I understand (especially how D4 or D8 changes), but maybe
this
would get you closer:
Option Explicit
Sub SortMatch()
Dim wks As Worksheet
Dim TryCtr As Long
Dim MaxTries As Long
Dim SetCtr As Long
Dim MaxSets As Long
Set wks = ActiveSheet
MaxTries = 10
MaxSets = 3
Application.ScreenUpdating = False
With wks
.Columns(3).Insert
.Range("C1:C8").FormulaR1C1 = "=RAND()"
With .Range("A1:C8")
.Sort Key1:=.Columns(3), _
Order1:=xlAscending, _
Header:=xlGuess, _
OrderCustom:=1, _
MatchCase:=False, _
Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
End With
SetCtr = 0
TryCtr = 0
Do
'How could the line above be amended to
'handle the scenario where the
'condition is approximate, eg: stop the
'randomization if the absolute value
'of D4 is within 5% of D8's ?
'I think that this is the formula you're describing:
'=ABS((ABS(D4)/D8)-1)<=0.05
If IsNumeric(.Range("d8").Value) = False _
Or IsNumeric(.Range("d4").Value) = False Then
'what should happen
MsgBox "non-numerics in d4 and/or d8"
Exit Do
Else
If .Range("d8").Value = 0 Then
'what should happen?
MsgBox "D8 is 0"
Exit Do
Else
If Abs((Abs(.Range("D4").Value) / .Range("D8").Value) -
1) _
<= 0.05 Then
.Columns(3).Delete
MsgBox "Found one set"
SetCtr = SetCtr + 1
.Range("A1:C8").PrintOut preview:=True
If SetCtr >= MaxSets Then
Exit Do
End If
End If
End If
End If
TryCtr = TryCtr + 1
If TryCtr > MaxTries Then
MsgBox "Too many tries"
Exit Do
End If
Loop
End With
Application.ScreenUpdating = True
End Sub