Your problem is a timing issue, the clue is the fact you get the correct answer when you step through it. You are looping through picking up cells from the worksheet doing some calculations , then writing cells back to the worksheet doing some more ca lculations then picking up the same cells again and doing more calculations, the trouble is that sometimes when you pick the cell up for the second time it hasn't updated from when you wrote it. The way to solve this is to load all of the cells you are using into a variant array and do the whole calculation in VBA and only write back to the spreadsheet at the end. Note this is a much faster way of doing the calculation anyway , you should always do yor calculation like this. So try this code. I get the same answer every time with this code:
Sub filanoua2()
Dim matrix(20) As Double
Dim matrixindicator As Integer
Dim sumamatrice As Double
Dim sumaintermediara As Double
matrixindicator = 1
Dim tester As Integer
Dim Wrange As Variant
Worksheets("filenoua").Select
Wrange = Worksheets("filenoua").Range(Cells(1, 1), Cells(400, 25))
tester = 0
For q = 1 To 40
For w = 1 To 10
If Wrange((q - 1) * 10 + w, 6) = "" Then Exit Sub
Wrange((q - 1) * 10 + w, 13) = (Wrange((q - 1) * 10 + 1, 22)) / 10 / (Wrange((q - 1) * 10 + w, 6) - 1) ' poata sa fie -1 sau fara
If Wrange((q - 1) * 10 + w, 3) = Wrange((q - 1) * 10 + w, 4) Then Wrange((q - 1) * 10 + w, 20) = Wrange((q - 1) * 10 + w, 6) * Wrange((q - 1) * 10 + w, 13) - Wrange((q - 1) * 10 + w, 13)
If Wrange((q - 1) * 10 + w, 3) <> Wrange((q - 1) * 10 + w, 4) Then Wrange((q - 1) * 10 + w, 20) = -1 * Wrange((q - 1) * 10 + w, 13)
sumaintermediara = suma((q - 1) * 10 + 1, w - 1)
If sumaintermediara >= Abs(sumamatrice) And w <> 0 And tester = 0 Then
Wrange((q - 1) * 10 + 1, 22) = Wrange(1, 22)
matrixindicator = 1
sumamatrice = 0
tester = 1
End If
Next w
If tester = 0 Then sumaintermediara = 0
Wrange(q * 10 + 1, 22) = suma((q - 1) * 10 + 1, (q - 1) * 10 + 10)
If Wrange(q * 10 + 1, 22) + sumaintermediara > Abs(sumamatrice) Then
Wrange(q * 10 + 1, 23) = Wrange(q * 10 + 1, 22)
Wrange(q * 10 + 1, 22) = Wrange(1, 22)
matrixindicator = 1
sumamatrice = 0
tester = 0
sumaintermediara = 0
End If
If Wrange(q * 10 + 1, 22) + sumaintermediara < Abs(sumamatrice) Then
matrix(matrixindicator) = Wrange(q * 10 + 1, 22)
matrixindicator = matrixindicator + 1
sumamatrice = 0
For bn = 1 To matrixindicator - 1
sumamatrice = sumamatrice + matrix(bn)
Next bn
Wrange(q * 10 + 1, 23) = Wrange(q * 10 + 1, 22)
Wrange(q * 10 + 1, 22) = -10 * sumamatrice
tester = 0
sumaintermediara = 0
End If
Next q
Worksheets("filenoua").Range(Cells(1, 1), Cells(400, 25)) = Wrange
End Sub