Advertisement
Alx09

Untitled

Aug 25th, 2023
888
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.21 KB | None | 0 0
  1. Sub Buton2_Clic()
  2.     Dim sumaCautata As Double
  3.     Dim coloana As Range
  4.    
  5.     sumaCautata = InputBox("Introduceti suma pe care doriti sa o atingeti:")
  6.     Set coloana = Range("A1:A" & Cells(Rows.Count, 1).End(xlUp).Row)
  7.    
  8.     ClearColumnC2 ' Cură?ăm coloana C2 înainte de a începe
  9.    
  10.    Dim usedRows() As Boolean
  11.    ReDim usedRows(1 To coloana.Rows.Count) As Boolean
  12.    
  13.    FindSums coloana, sumaCautata, 1, "", 0, usedRows
  14. End Sub
  15.  
  16. Sub FindSums(coloana As Range, sumaCautata As Double, rowIndex As Long, indices As String, currentSum As Double, usedRows() As Boolean)
  17.    Dim celula As Range
  18.    Dim i As Long
  19.    
  20.    For i = rowIndex To coloana.Rows.Count
  21.        Set celula = coloana.Cells(i, 1)
  22.        
  23.        If celula.Value <> "" And celula.Value > 0 And IsNumeric(celula.Value) And Not usedRows(i) Then
  24.            Dim newSum As Double
  25.            newSum = currentSum + celula.Value
  26.            
  27.            If newSum = sumaCautata Then
  28.                WriteIndices indices & celula.Row & " " ' Înregistrăm indicele rândului
  29.                 usedRows(i) = True
  30.                 Exit Sub ' Ie?im din bucla când găsim o solu?ie
  31.            ElseIf newSum < sumaCautata Then
  32.                usedRows(i) = True
  33.                currentSum = newSum
  34.                indices = indices & celula.Row & " "
  35.            End If
  36.        End If
  37.    Next i
  38. End Sub
  39.  
  40. Sub WriteIndices(indices As String)
  41.    Dim sortedIndices() As String
  42.    sortedIndices = Split(Trim(indices))
  43.    Dim i As Long, j As Long, temp As String
  44.    
  45.    ' Sortăm indicii crescător
  46.     For i = LBound(sortedIndices) To UBound(sortedIndices) - 1
  47.         For j = i + 1 To UBound(sortedIndices)
  48.             If CLng(sortedIndices(i)) > CLng(sortedIndices(j)) Then
  49.                 temp = sortedIndices(i)
  50.                 sortedIndices(i) = sortedIndices(j)
  51.                 sortedIndices(j) = temp
  52.             End If
  53.         Next j
  54.     Next i
  55.    
  56.     Dim lastRow As Long
  57.     lastRow = Range("C" & Rows.Count).End(xlUp).Row + 1
  58.    
  59.     ' Adăugăm indicii ordona?i în coloana C2
  60.    Range("C" & lastRow).Value = Join(sortedIndices, " ")
  61. End Sub
  62.  
  63. Sub ClearColumnC2()
  64.    Range("C:C").ClearContents
  65. End Sub
  66.  
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement