from c# to vba conversion (yes, kind of stupid)
double [] numbers = new numbers[200];
numbers[0] = 123;
numbers[1] = 456;
//
// and so on.
//
var n0 = numbers;
var n1 = numbers.Skip(1);
var n2 = numbers.Skip(2);
var n3 = numbers.Skip(3);
var x = from a in n0
from b in n1
from c in n2
from d开发者_开发百科 in n3
where a + b + c + d == 2341.42
select new { a1 = a, b1 = b, c1 = c, d1 = d };
foreach (var aa in x)
{
Console.WriteLine("{0}, {1}, {2}, {3}", aa.a1, aa.b1, aa.c1, aa.d1 );
}
there's my c# code. i need to transate it into vba.
my main problem is this:
var x = from a in n0
from b in n1
from c in n2
from d in n3
where a + b + c + d == 2341.42
select new { a1 = a, b1 = b, c1 = c, d1 = d };
how would we do this in vba?
Type NumberSet
A As Double
B As Double
C As Double
D As Double
End Type
Public Sub TheSub()
Dim numbers(0 To 199) As Double
numbers(0) = 123
numbers(1) = 456
'
' and so on.
'
'iterators
Dim ai As Integer
Dim bi As Integer
Dim ci As Integer
Dim di As Integer
'data set
Dim x() As NumberSet
'temp record holder
Dim ns As NumberSet
Dim count As Integer
count = 0
'simulate the select query
For ai = LBound(numbers) To UBound(numbers)
For bi = LBound(numbers) + 1 To UBound(numbers)
For ci = LBound(numbers) + 2 To UBound(numbers)
For di = LBound(numbers) + 3 To UBound(numbers)
'fill the record
With ns
.A = numbers(ai)
.B = numbers(bi)
.C = numbers(ci)
.D = numbers(di)
'test record
If .A + .B + .C + .D = 2341.42 Then
'append to the data set
ReDim Preserve x(0 To count)
x(count) = ns
count = count + 1
End If
End With
Next di
Next ci
Next bi
Next ai
'iterate through data set and print results
For i = LBound(x) To UBound(x)
ns = x(i)
With ns
Debug.Print .A & ", " & .B & ", " & .C & ", " & .D
End With
Next i
End Sub
not the most efficient.. but tried to follow the flow of the original code.. it will run slow as it's like bruteforce looping (takes about four minutes here).. perhaps using a temporary database/access table via ADO/DAO where you could use SQL would help.
Dim N(200)
For I0 = 0 To 199
For I1 = 1 To 199
For I2 = 2 To 199
For I3 = 3 To 199
If N(I0)+N(I1)+N(I2)+N(I3) = 2341.42 Then
Debug.Print N(I0) & "," & N(I1) & "," & N(I2) & "," & N(I3)
End If
Next
Next
Next
Next
精彩评论