Option Explicit
Sub TotalisationParAnnee()
   Dim d1 As Object, d2 As Object, d3 As Object
   Dim i As Long
   Dim T1, T2, key, keys
   Dim Sh1 As Worksheet, Sh2 As Worksheet, Sh3 As Worksheet
   Set Sh1 = ThisWorkbook.Sheets("FEC- 2023")
   Set Sh2 = ThisWorkbook.Sheets("FEC- 2024")
   Set Sh3 = ThisWorkbook.Sheets("Résultat")
   Set d1 = CreateObject("Scripting.Dictionary")
   Set d2 = CreateObject("Scripting.Dictionary")
   Set d3 = CreateObject("Scripting.Dictionary")
   T1 = Sh1.Range("A1").CurrentRegion
   T2 = Sh2.Range("A1").CurrentRegion
   ' année 2023
   For i = 2 To UBound(T1)
      If T1(i, 12) <> "" Then
         key = T1(i, 5) & "|" & T1(i, 6)
         d1(key) = d1(key) + (T1(i, 12) - T1(i, 13))
      End If
   Next i
   ' année 2024
   For i = 2 To UBound(T2)
      If T2(i, 12) <> "" Then
         key = T2(i, 5) & "|" & T2(i, 6)
         d2(key) = d2(key) + (T2(i, 12) - T2(i, 13))
      End If
   Next i
   Debug.Print d1.Count, d2.Count
   ' Combiner 2023 et 2024
   For Each key In d1.keys
      If d2.Exists(key) Then
         d3(key) = Array(d1(key), d2(key))
      Else
         d3(key) = Array(d1(key), 0)
      End If
   Next key
   For Each key In d2.keys
      If Not d1.Exists(key) Then
         d3(key) = Array(0, d2(key))
      End If
   Next key
   ' Report résultat
   With Sh3
      .Cells.Clear
      .[A1] = "Comptes"
      .[B1] = "Libellés"
      .[C1] = Right(Sh1.Name, 4)
      .[d1] = Right(Sh2.Name, 4)
      Dim row As Long
      row = 2
      For Each key In d3.keys
         keys = Split(key, "|")
         .Cells(row, 1).Value = keys(0)     ' Première partie de la clé
         .Cells(row, 2).Value = keys(1)     ' Deuxième partie de la clé
         .Cells(row, 3).Value = d3(key)(0)  ' Valeur de d1
         .Cells(row, 4).Value = d3(key)(1)  ' Valeur de d2
         row = row + 1
      Next key
      ' Format numérique avec 2 décimales et séparateur de milliers
      .Columns(3).NumberFormat = "#,##0.00"
      .Columns(4).NumberFormat = "#,##0.00"
      .Range("C1:D1").NumberFormat = "General"
      .Columns("A:D").AutoFit
      .Range("A1:D1").Font.Bold = True
      .Range("A1").CurrentRegion.Borders.Weight = xlThin
   End With
   Set Sh1 = Nothing: Set Sh2 = Nothing: Set Sh3 = Nothing
   Set d1 = Nothing: Set d2 = Nothing: Set d3 = Nothing
   MsgBox "Traitement terminé!"
End Sub