Make control array in code - vb6

This code does not work I want to create a control array on my Form_Load in VB6 because I have to make 225 of them for a scrabble board and they have to be precise. My code is:
Private lblblocks(1 To 225) As Label
Private Sub Form_Load()
Dim i As Integer, j As Integer
For i = 1 To 15
For j = 1 To 15
Dim arrnum As Integer
arrnum = (i - 1) * 15 + j
Load lblblocks(arrnum)
With lblblocks(arrnum)
.Width = 1000
.Height = 1000
.Top = (i - 1) * 1000
.Left = (j - 1) * 1000
.Visible = True
.BackColor = Int(Rnd(1) * 255) + &H100 * Int(Rnd(1) * 255) + &H10000 * Int(Rnd(1) * 255)
End With
Next j
Next i
End Sub
I used the backcolor to see all my label boxes. This code does not work. I get an error "Object variable or With block variable not set". Any help? I don't know what is wrong. I would like to keep the label boxes in a control array I know how to do it without making it a control array.

Cody Gray had it correct in his comment. I don't believe you can create a control array on the fly only in code in VB6. You have to place one instance of the control on the form and give it an Index property value of zero. This creates a control array with only one element, at index zero. You can then modify your code to produce the desired result, like so:
Private Sub Form_Load()
Dim i As Integer
Dim j As Integer
For i = 0 To 14
For j = 0 To 14
Dim tileIdx As Integer
tileIdx = i * 15 + j
'If the tile index is zero, we already have that control,
'so there's no need to load new instance. Otherwise, use the
'Load method to create a new control in the array with the
'specified index.
If tileIdx > 0 Then
Load lblTile(tileIdx)
End If
With lblTile(tileIdx)
.Width = 1000
.Height = 1000
.Top = i * 1000
.Left = j * 1000
.Visible = True
.BackColor = Int(Rnd(1) * 255) + &H100 * Int(Rnd(1) * 255) + &H10000 * Int(Rnd(1) * 255)
End With
Next
Next
End Sub
As noted in the comment, you don't need to load another instance of the control at array index zero because you did that at design time. I also iterated my array starting from zero for slightly easier calculation of the indices.

we can add from scratch
Private Sub Command3_Click()
Dim rownum As Integer, ColNum As Integer
'Dim lblblocks(1 To 225) As Label
Dim lblblocks() As Label
Dim wwidth As Integer, hheight As Integer
wwidth = 400: hheight = 200
Dim i As Integer, j As Integer
rownum = 20: ColNum = 25
ReDim lblblocks(1 To rownum * ColNum)
For i = 1 To rownum
For j = 1 To ColNum
Dim arrnum As Integer
arrnum = (i - 1) * ColNum + j
Set lblblocks(arrnum) = Me.Controls.Add("VB.Label", "LB" & arrnum)
With lblblocks(arrnum)
'Set Bb(i) = formname.Controls.Add("VB.CommandButton", "Bb" & i)
.Width = wwidth
.Height = hheight
'.Top = (i - 1) * 100
'.Left = (j - 1) * 400
.Top = (i) * hheight
.Left = (j) * wwidth
.Caption = arrnum
.Visible = True
.BackColor = Int(Rnd(1) * 255) + &H100 * Int(Rnd(1) * 255) + &H10000 * Int(Rnd(1) * 255)
End With
Next j
Next i
End Sub

Related

Visual Studio - vb console application. my program keepr crashing with code 0 and i dont know what to do

im using console. ive written code its for my exam and im not very good at it but ive tried and no matter what i do i cant get the program to stop crashing. it keeps crashing at code 0 and im really frustrated please help me ive attached the code below
Module Module1
Sub Main()
Dim discount As Integer = 0
Dim freetickets As Integer = 0
Dim estimatedcost As Integer = 0
Dim totalstudents As Integer = 0
Dim coachcost As Integer = 550
Dim entryticket As Integer = 30
Dim name(45) As String
Dim paidstatus(45) As Boolean
Dim studentspaid As Integer = 0
Dim totalcost As Integer = 0
Dim collectedcost As Integer = 0
Dim finalcost As Integer = 0
Console.WriteLine("Enter Student Name")
name(45) = Console.ReadLine()
Console.WriteLine("has the student paid? (true/false)")
paidstatus(45) = Console.ReadLine()
If paidstatus(45) = True Then
studentspaid = studentspaid + 1
totalstudents = totalstudents + 1
ElseIf paidstatus(45) = False Then
totalstudents = totalstudents + 1
End If
totalcost = (totalstudents * 30) + (550 / totalstudents)
If totalstudents = 45 Then
If studentspaid = 10 Then
freetickets = freetickets + 1
End If
If studentspaid = 20 Then
freetickets = freetickets + 1
End If
If studentspaid = 30 Then
freetickets = freetickets + 1
End If
If studentspaid = 40 Then
freetickets = freetickets + 1
End If
collectedcost = (studentspaid * 30) + (550 / studentspaid)
discount = (freetickets * 30) - (550 / studentspaid)
finalcost = totalcost - collectedcost - discount
If finalcost > 0 Then
Console.WriteLine("loss of")
Console.WriteLine(-finalcost)
End If
If finalcost = 0 Then
Console.WriteLine("broken even")
End If
If finalcost < 0 Then
Console.WriteLine("profit of")
Console.WriteLine(finalcost)
End If
End If
End Sub
End Module

Visual Basic 6 Game "21" not displaying MsgBox when necessary

Trying to make the game "21" in visual basic 6, i have everything done but MsgBox is not displaying when its Bust, or Blackjack. Any ideas?
Private Sub cmdCheckScore_Click()
lblPC1.Visible = True
lblPC2.Visible = True
lblPC3.Visible = True
End Sub
Private Sub cmdDrawCard_Click()
If lblDraw1.Caption = "" Then 'Draws 3 random numbers with 3 button clicks
intDraw1 = Int(Rnd * 10 + 1)
lblDraw1.Caption = intDraw1
ElseIf lblDraw2.Caption = "" Then
intDraw2 = Int(Rnd * 10 + 1)
lblDraw2.Caption = intDraw2
ElseIf lblDraw3.Caption = "" Then
intDraw3 = Int(Rnd * 10 + 1)
lblDraw3.Caption = intDraw3
End If
intPlayerScore = intPlayer1 + intPlayer2 + intDraw1 + intDraw2 + intDraw3
intComputerScore = intPC1 + intPC2 + intPC3
If intPlayerScore > 21 Then
MsgBox "Bust!"
ElseIf intPlayerScore = 21 Then
MsgBox "Blackjack!"
End If
End Sub
Private Sub Form_Load()
Randomize
Dim intPlayer1 As Integer
Dim intPlayer2 As Integer
Dim intPlayer3 As Integer
Dim intPC1 As Integer
Dim intPC2 As Integer
Dim intPC3 As Integer
Dim intDraw1 As Integer
Dim intDraw2 As Integer
Dim intDraw3 As Integer
Dim PlayerScore As Integer
Dim ComputerScore As Integer
intDraw1 = 0
intDraw2 = 0
intDraw3 = 0
intPlayer1 = Int(Rnd * 10 + 1)
intPlayer2 = Int(Rnd * 10 + 1)
lblPlayer1.Caption = intPlayer1
lblPlayer2.Caption = intPlayer2
intPC1 = Int(Rnd * 10 + 1)
intPC2 = Int(Rnd * 10 + 1)
intPC3 = Int(Rnd * 10 + 1)
lblPC1.Caption = intPC1
lblPC2.Caption = intPC2
lblPC3.Caption = intPC3
End Sub
I've been trying to figure this out for 2 hours, and still no solution.
I believe your variables are getting created out of scope, and therefore when the click code runs, they're all variants.
Move your declares out of Form_Load to above cmdCheckScore
Dim intPlayer1 As Integer 'at the top of your FORM
Dim intPlayer2 As Integer
Dim intPlayer3 As Integer
Dim intPC1 As Integer
Dim intPC2 As Integer
Dim intPC3 As Integer
Dim intDraw1 As Integer
Dim intDraw2 As Integer
Dim intDraw3 As Integer
Dim PlayerScore As Integer
Dim ComputerScore As Integer 'at the top of your FORM
Private Sub cmdCheckScore_Click()
Next, click off to the left and set a breakpoint on this line to verify the values are getting there!
intPlayerScore = intPlayer1 + intPlayer2 + intDraw1 + intDraw2 + intDraw3

check if control exists on the left side of another control

How can i find if a control exists on the left side of another control.
For example we usually place labels on the left to text box. in my from I have more than 50
controls and i want to enlarge them. Enlarging one by one is time consuming. How can i find a control and its width, placed left to another. Can anyone suggest an way to achieve this in code. I am using vb6. This is my code and this is not working
For Each crl In Me.Controls
'crl.Width = crl.Width + 750
If crl.Left < 150 Then
crl.Left = crl.Left + 2000
Else
crl.Left = (crl.Width / 2) + crl.Left + 1000
End If
crl.Top = crl.Top + 500
'crl.Height = crl.Height + 100
'crl.Width = crl.Width + 750
Next
Is there some logical structure in the layout of your controls?
If that is the case then you can use the Form_Resize() event to position (and resize) the controls
for example a form with 10 labels and 10 textboxes in a layout of 5 x 2 rows x columns
'1 form with:
'1 textbox : name=Text1 Index=0
'1 label : name=Label1 Index=0
Option Explicit
Private Sub Form_Load()
Dim intIndex As Integer
'load extra labels and textboxes
For intIndex = 1 To 9
Load Label1(intIndex)
Label1(intIndex).Caption = "Label" & CStr(intIndex + 1)
Label1(intIndex).Visible = True
Load Text1(intIndex)
Text1(intIndex).Text = "Text" & CStr(intIndex + 1)
Text1(intIndex).Visible = True
Next intIndex
End Sub
Private Sub Form_Resize()
Dim intIndex As Integer
Dim intRow As Integer, intCol As Integer
Dim sngWidth As Single, sngHeight As Single
'calculate width and height of each control
sngWidth = ScaleWidth / 4
sngHeight = ScaleHeight / 5
'loop through all controls and position and resize them
For intIndex = 0 To 9
intCol = intIndex \ 5
intRow = intIndex Mod 5
Label1(intIndex).Move 2 * intCol * sngWidth, intRow * sngHeight, sngWidth, sngHeight
Text1(intIndex).Move (2 * intCol + 1) * sngWidth, intRow * sngHeight, sngWidth, sngHeight
Next intIndex
End Sub

Drawing a circle with radial lines

for i = 0 to 23
'' ...
'' create 'line' control
'' ...
line.x1 = (inner_radius*cos(15 * i)) + centerx
line.y1 = (inner_radius*sin(15 * i)) + centery
line.x2 = (outer_radius*cos(15 * i)) + centerx
line.y2 = (outer_radius*sin(15 * i)) + centery
next
I'm using this algorithm to render many line controls to make something like the following:
The result is rather bizarre:
I think this happens due to the rounding of the cos() and sin() functions, so my question is, is there some algorithm I can apply to fix the rounding? Or is there a better way to render such controls, perhaps?
EDIT:
The problem, as pointed by Hrqls was that I was using degrees instead of radians... this is the function that I ended up using:
Sub ProgressAnim(ByVal centerx, _
ByVal centery, _
ByVal outer_radius, _
ByVal inner_radius, _
ByVal step_count, _
ByVal line_width)
Dim pi
Dim degstep
Dim scan
Dim newcontrol As Line
Dim controlid
pi = 4 * Atn(1)
degstep = pi / (step_count / 2)
For scan = 0 To step_count - 1
controlid = "line" & (scan + 1)
Set newcontrol = Me.Controls.Add("vb.line", controlid)
newcontrol.X1 = centerx + (inner_radius * Cos(degstep * scan))
newcontrol.Y1 = centery + (inner_radius * Sin(degstep * scan))
newcontrol.X2 = centerx + (outer_radius * Cos(degstep * scan))
newcontrol.Y2 = centery + (outer_radius * Sin(degstep * scan))
newcontrol.BorderStyle = 1
newcontrol.BorderWidth = line_width
newcontrol.Visible = True
Next
End Sub
Calling it like this
ProgressAnim 150, 250, 16, 9, 18, 1
produces this:
which is much closer to what I expected... sadly, I still don't know how to achieve anti-aliasing, but this will do. (For the moment, at least) :)
Your problem is that you calculate the angles in degrees while VB uses radians for its angles
have a look at the following project :
Option Explicit
Private Sub Form_Click()
DrawWheel
End Sub
Private Sub DrawWheel()
Dim intI As Integer
Dim sngRadius As Single
Dim sngRadiusY As Single
Dim sngCenterX As Single, sngCenterY As Single
Dim sngX1 As Single, sngY1 As Single
Dim sngX2 As Single, sngY2 As Single
Dim sngStep As Single
Dim sngAngle As Single
Dim sngCos As Single, sngSin As Single
'calculate form sizes
sngRadius = (ScaleWidth - 240) / 2
sngRadiusY = (ScaleHeight - 240) / 2
sngCenterX = 120 + sngRadius
sngCenterY = 120 + sngRadiusY
If sngRadiusY < sngRadius Then sngRadius = sngRadiusY
'draw circle
Circle (sngCenterX, sngCenterY), sngRadius
'calculate step between lines
sngStep = Atn(1) / 3
'draw lines
For intI = 0 To 23
'calculate angle for each line
sngAngle = sngStep * intI
'calculate coordinates for each line
sngCos = Cos(sngAngle)
sngSin = Sin(sngAngle)
sngX1 = sngCenterX + sngCos * sngRadius / 10
sngY1 = sngCenterY + sngSin * sngRadius / 10
sngX2 = sngCenterX + sngCos * sngRadius
sngY2 = sngCenterY + sngSin * sngRadius
'draw each lines
Line (sngX1, sngY1)-(sngX2, sngY2)
'print sequence number
Print CStr(intI)
Next intI
End Sub
Click on the form to draw the wheel
Atn(1) is PI/4 ... For 24 lines you need to divide 2*PI by 24 .. thus you need to divide PI by 12 ... which makes you divide Atn(1) by 3
change for i = 0 to 23 to for i = 0 to 21
and (15 * i) with (0.3 * i)
Try that code in form1 with a timer1:
Dim c As Integer, centerx As Integer, centery As Integer, inner_radius As Integer, outer_radius As Integer
Dim x1 As Single, y1 As Single, x2 As Single, y2 As Single
Private Sub Form_Load()
c = 0
centerx = Form1.Width / 2
centery = Form1.Height / 2
inner_radius = 1200
outer_radius = 1
Timer1.Interval = 200
End Sub
Private Sub Timer1_Timer()
x1 = (inner_radius * Cos(0.3 * c)) + centerx
y1 = (inner_radius * Sin(0.3 * c)) + centery
x2 = (outer_radius * Cos(0.3 * c)) + centerx
y2 = (outer_radius * Sin(0.3 * c)) + centery
Line (x1, y1)-(x2, y2), RGB(0, 0, 0)
c = c + 1
If c = 21 Then Timer1.Enabled = False
End Sub
check your numbers in this example to see the drawing behavior.
I would ensure that you keep the greatest accuracy by using proper fractions of 2PI.
Fiddle with the constants until you get roughly what you want:
Option Explicit
Private Sub Form_Load()
Timer.Interval = 50
End Sub
Private Sub Timer_Timer()
DrawRadialLines
End Sub
Private Sub DrawRadialLines()
Const ksngPI As Single = 3.14159!
Const ksngCircle As Single = 2! * ksngPI
Const ksngInnerRadius As Single = 130!
Const ksngOuterRadius As Single = 260!
Const ksngCenterX As Single = 1200!
Const ksngCenterY As Single = 1200!
Const klSegmentCount As Long = 12
Const klLineWidth As Long = 3
Static s_lActiveSegment As Integer ' The "selected" segment.
Dim lSegment As Long
Dim sngRadians As Single
Dim sngX1 As Single
Dim sngY1 As Single
Dim sngX2 As Single
Dim sngY2 As Single
Dim cLineColour As OLE_COLOR
Me.DrawWidth = klLineWidth
' Overdraw previous graphic.
Me.Line (ksngCenterX - ksngOuterRadius - Screen.TwipsPerPixelX * 2, ksngCenterY - ksngOuterRadius - Screen.TwipsPerPixelY * 2)-(ksngCenterX + ksngOuterRadius + Screen.TwipsPerPixelX * 2, ksngCenterY + ksngOuterRadius + Screen.TwipsPerPixelY * 2), Me.BackColor, BF
For lSegment = 0 To klSegmentCount - 1
'
' Work out the coordinates for the line to be draw from the outside circle to the inside circle.
'
sngRadians = (ksngCircle * CSng(lSegment)) / klSegmentCount
sngX1 = (ksngOuterRadius * Cos(sngRadians)) + ksngCenterX
sngY1 = (ksngOuterRadius * Sin(sngRadians)) + ksngCenterY
sngX2 = (ksngInnerRadius * Cos(sngRadians)) + ksngCenterX
sngY2 = (ksngInnerRadius * Sin(sngRadians)) + ksngCenterY
' Work out how many segments away from the "current segment" we are.
' The current segment should be the darkest, and the further away from this segment we are, the lighter the colour should be.
Select Case Abs(Abs(s_lActiveSegment - lSegment) - klSegmentCount \ 2)
Case 0!
cLineColour = RGB(0, 0, 255)
Case 1!
cLineColour = RGB(63, 63, 255)
Case 2!
cLineColour = RGB(117, 117, 255)
Case Else
cLineColour = RGB(181, 181, 255)
End Select
Me.Line (sngX1, sngY1)-(sngX2, sngY2), cLineColour
Next lSegment
' Move the current segment on by one.
s_lActiveSegment = (s_lActiveSegment + 1) Mod klSegmentCount
End Sub

Memory and execution time reduction for algorithms

I have been asked to ask this question again and in a little different context. This is the previous post:
Filtering in VBA after finding combinations
I would like to make this code possible with 100 different variables without having excel run out of memory and reducing the execution time significantly.
The problem with the code below is that if I have 100 boxes, excel will run out of memory in the line "Result(0 To 2 ^ NumFields - 2)" ( The code works for < 10 boxes)
This is my input:
3 A B C D E ...
7.7 3 1 1 1 2 ...
5.5 2 1 2 3 3 ...
This is the code:
Function stackBox()
Dim ws As Worksheet
Dim width As Long
Dim height As Long
Dim numOfBox As Long
Dim optionsA() As Variant
Dim results() As Variant
Dim str As String
Dim outputArray As Variant
Dim i As Long, j As Long
Dim currentSymbol As String
'------------------------------------new part----------------------------------------------
Dim maxHeight As Double
Dim maxWeight As Double
Dim heightarray As Variant
Dim weightarray As Variant
Dim totalHeight As Double
Dim totalWeight As Double
'------------------------------------new part----------------------------------------------
Set ws = Worksheets("Sheet1")
With ws
'clear last time's output
height = .Cells(.Rows.Count, 1).End(xlUp).row
If height > 3 Then
.Range(.Cells(4, 1), .Cells(height, 1)).ClearContents
End If
numOfBox = .Cells(1, 1).Value
width = .Cells(1, .Columns.Count).End(xlToLeft).Column
If width < 2 Then
MsgBox "Error: There's no item, please fill your item in Cell B1,C1,..."
Exit Function
End If
'------------------------------------new part----------------------------------------------
maxHeight = .Cells(2, 1).Value
maxWeight = .Cells(3, 1).Value
ReDim heightarray(1 To 1, 1 To width - 1)
ReDim weightarray(1 To 1, 1 To width - 1)
heightarray = .Range(.Cells(2, 2), .Cells(2, width)).Value
weightarray = .Range(.Cells(3, 2), .Cells(3, width)).Value
'------------------------------------new part----------------------------------------------
ReDim optionsA(0 To width - 2)
For i = 0 To width - 2
optionsA(i) = .Cells(1, i + 2).Value
Next i
GenerateCombinations optionsA, results, numOfBox
' copy the result to sheet only once
ReDim outputArray(1 To UBound(results, 1) - LBound(results, 1) + 1, 1 To 1)
Count = 0
For i = LBound(results, 1) To UBound(results, 1)
If Not IsEmpty(results(i)) Then
'rowNum = rowNum + 1
str = ""
totalHeight = 0#
totalWeight = 0#
For j = LBound(results(i), 1) To UBound(results(i), 1)
currentSymbol = results(i)(j)
str = str & currentSymbol 'results(i)(j) is the SYMBOL e.g. A, B, C
'look up box's height and weight , increment the totalHeight/totalWeight
updateParam currentSymbol, optionsA, heightarray, weightarray, totalHeight, totalWeight
Next j
If totalHeight < maxHeight And totalWeight < maxWeight Then
Count = Count + 1
outputArray(Count, 1) = str
End If
'.Cells(rowNum, 1).Value = str
End If
Next i
.Range(.Cells(4, 1), .Cells(UBound(outputArray, 1) + 3, 1)).Value = outputArray
End With
End Function
Sub updateParam(ByRef targetSymbol As String, ByRef symbolArray As Variant, ByRef heightarray As Variant, ByRef weightarray As Variant, ByRef totalHeight As Double, ByRef totalWeight As Double)
Dim i As Long
Dim index As Long
index = -1
For i = LBound(symbolArray, 1) To UBound(symbolArray, 1)
If targetSymbol = symbolArray(i) Then
index = i
Exit For
End If
Next i
If index <> -1 Then
totalHeight = totalHeight + heightarray(1, index + 1)
totalWeight = totalWeight + weightarray(1, index + 1)
End If
End Sub
Sub GenerateCombinations(ByRef AllFields() As Variant, _
ByRef Result() As Variant, ByVal numOfBox As Long)
Dim InxResultCrnt As Integer
Dim InxField As Integer
Dim InxResult As Integer
Dim i As Integer
Dim NumFields As Integer
Dim Powers() As Integer
Dim ResultCrnt() As String
NumFields = UBound(AllFields) - LBound(AllFields) + 1
ReDim Result(0 To 2 ^ NumFields - 2) ' one entry per combination
ReDim Powers(0 To NumFields - 1) ' one entry per field name
' Generate powers used for extracting bits from InxResult
For InxField = 0 To NumFields - 1
Powers(InxField) = 2 ^ InxField
Next
For InxResult = 0 To 2 ^ NumFields - 2
' Size ResultCrnt to the max number of fields per combination
' Build this loop's combination in ResultCrnt
ReDim ResultCrnt(0 To NumFields - 1)
InxResultCrnt = -1
For InxField = 0 To NumFields - 1
If ((InxResult + 1) And Powers(InxField)) <> 0 Then
' This field required in this combination
InxResultCrnt = InxResultCrnt + 1
ResultCrnt(InxResultCrnt) = AllFields(InxField)
End If
Next
If InxResultCrnt = 0 Then
Debug.Print "testing"
End If
'additional logic here
If InxResultCrnt >= numOfBox Then
Result(InxResult) = Empty
Else
' Discard unused trailing entries
ReDim Preserve ResultCrnt(0 To InxResultCrnt)
' Store this loop's combination in return array
Result(InxResult) = ResultCrnt
End If
Next
End Sub
Here's a version that does all the heavy lifting in variant arrays
(Combinations logic based on this answer for This Answer by Joubarc)
This runs on a sample dataset of 100 boxes with > 40,000 returned, and in < 1 second
Notes:
Execution time rises quickly if the Max number of boxes increases (eg 4 from 100: approx 13s)
If the number of returned results exceeds 65535, the code to tranpose the array into the sheet fails (last line of the sub) If you need to handle this may results, you will need to change the way results are returned to the sheet
Sub Demo()
Dim rNames As Range
Dim rHeights As Range
Dim rWeights As Range
Dim aNames As Variant
Dim aHeights As Variant
Dim aWeights As Variant
Dim MaxNum As Long
Dim MaxHeight As Double
Dim MaxWeight As Double
' *** replace these six line with your data ranges
Set rNames = Range([F5], [F5].End(xlToRight))
Set rHeights = rNames.Offset(1, 0)
Set rWeights = rNames.Offset(2, 0)
MaxNum = [C5]
MaxHeight = [C6]
MaxWeight = [C7]
aNames = rNames
aHeights = rHeights
aWeights = rWeights
Dim Result() As Variant
Dim n As Long, m As Long
Dim i As Long, j As Long
Dim iRes As Long
Dim res As String
Dim TestCombin() As Long
Dim TestWeight As Double
Dim TestHeight As Double
Dim idx() As Long
' Number of boxes
ReDim TestCombin(0 To MaxNum - 1)
n = UBound(aNames, 2) - LBound(aNames, 2) + 1
' estimate size of result array = number of possible combinations
For m = 1 To MaxNum
i = i + Application.WorksheetFunction.Combin(n, m)
Next
ReDim Result(1 To 3, 1 To i)
' allow for from 1 to MaxNum of boxes
iRes = 1
For m = 1 To MaxNum
ReDim idx(0 To m - 1)
For i = 0 To m - 1
idx(i) = i
Next i
Do
'Test current combination
res = ""
TestWeight = 0#
TestHeight = 0#
For j = 0 To m - 1
'Debug.Print aNames(1, idx(j) + 1);
res = res & aNames(1, idx(j) + 1)
TestWeight = TestWeight + aWeights(1, idx(j) + 1)
TestHeight = TestHeight + aHeights(1, idx(j) + 1)
Next j
'Debug.Print
If TestWeight <= MaxWeight And TestHeight <= MaxHeight Then
Result(1, iRes) = res
' optional, include actual Height and Weight in result
Result(2, iRes) = TestHeight
Result(3, iRes) = TestWeight
iRes = iRes + 1
End If
' Locate last non-max index
i = m - 1
While (idx(i) = n - m + i)
i = i - 1
If i < 0 Then
'All indexes have reached their max, so we're done
Exit Do
End If
Wend
'Increase it and populate the following indexes accordingly
idx(i) = idx(i) + 1
For j = i To m - 1
idx(j) = idx(i) + j - i
Next j
Loop
Next
' Return Result to sheet
Dim rng As Range
ReDim Preserve Result(1 To 3, 1 To iRes)
' *** Adjust returnm range to suit
Set rng = [E10].Resize(UBound(Result, 2), UBound(Result, 1))
rng = Application.Transpose(Result)
End Sub

Resources