Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Sub Buton2_Clic()
- Dim sumaCautata As Double
- Dim coloana As Range
- sumaCautata = InputBox("Introduceti suma pe care doriti sa o atingeti:")
- Set coloana = Range("A1:A" & Cells(Rows.Count, 1).End(xlUp).Row)
- ClearColumnC2 ' Cură?ăm coloana C2 înainte de a începe
- Dim usedRows() As Boolean
- ReDim usedRows(1 To coloana.Rows.Count) As Boolean
- FindSums coloana, sumaCautata, 1, "", 0, usedRows
- End Sub
- Sub FindSums(coloana As Range, sumaCautata As Double, rowIndex As Long, indices As String, currentSum As Double, usedRows() As Boolean)
- Dim celula As Range
- Dim i As Long
- For i = rowIndex To coloana.Rows.Count
- Set celula = coloana.Cells(i, 1)
- If celula.Value <> "" And celula.Value > 0 And IsNumeric(celula.Value) And Not usedRows(i) Then
- Dim newSum As Double
- newSum = currentSum + celula.Value
- If newSum = sumaCautata Then
- WriteIndices indices & celula.Row & " " ' Înregistrăm indicele rândului
- usedRows(i) = True
- Exit Sub ' Ie?im din bucla când găsim o solu?ie
- ElseIf newSum < sumaCautata Then
- usedRows(i) = True
- currentSum = newSum
- indices = indices & celula.Row & " "
- End If
- End If
- Next i
- End Sub
- Sub WriteIndices(indices As String)
- Dim sortedIndices() As String
- sortedIndices = Split(Trim(indices))
- Dim i As Long, j As Long, temp As String
- ' Sortăm indicii crescător
- For i = LBound(sortedIndices) To UBound(sortedIndices) - 1
- For j = i + 1 To UBound(sortedIndices)
- If CLng(sortedIndices(i)) > CLng(sortedIndices(j)) Then
- temp = sortedIndices(i)
- sortedIndices(i) = sortedIndices(j)
- sortedIndices(j) = temp
- End If
- Next j
- Next i
- Dim lastRow As Long
- lastRow = Range("C" & Rows.Count).End(xlUp).Row + 1
- ' Adăugăm indicii ordona?i în coloana C2
- Range("C" & lastRow).Value = Join(sortedIndices, " ")
- End Sub
- Sub ClearColumnC2()
- Range("C:C").ClearContents
- End Sub
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement