Option Compare Text 'la casse est ignorée
Sub Ventilation()
If Not IsDate([K1]) Then Exit Sub
Dim an%, mois As Byte, tablo, d As Object, i&, e, F As Worksheet, col%
Dim a(), b(), n&, colBudget%, colRecap%
an = Year([K1]): mois = Month([K1])
tablo = Sheets("RECAP").[A1].CurrentRegion.Resize(, 5) 'matrice, plus rapide
Set d = CreateObject("Scripting.Dictionary")
d.CompareMode = vbTextCompare 'la casse est ignorée
For i = 2 To UBound(tablo): d(tablo(i, 4)) = "": Next
On Error Resume Next
For Each e In d.keys
Set F = Nothing: Set F = Sheets(e)
col = 0: col = Application.Match(an, F.Rows(1), 0) + mois - 1
If col Then
'---filtrage---
d.RemoveAll 'nouvelle utilisation du Dictionary
ReDim a(1 To UBound(tablo), 1 To 1)
ReDim b(1 To UBound(tablo), 1 To 1)
n = 0
For i = 2 To UBound(tablo)
If tablo(i, 4) = e Then
n = n + 1
d(tablo(i, 3)) = "" 'liste des LIBELLES
a(n, 1) = tablo(i, 3)
b(n, 1) = tablo(i, 5)
End If
Next i
'---restitution dans le 1er tableau---
i = F.Cells(F.Rows.Count, 1).End(xlUp).Row + 1
F.Cells(i, 1).Resize(n) = a
F.Cells(i, col).Resize(n) = b
With F.Rows("3:" & i + n - 1)
.Sort .Columns(1), xlAscending, Header:=xlNo 'tri
For i = 1 To .Rows.Count
If Not d.exists(.Cells(i, 1).Value) Then .Cells(i, col) = "" 'effacement du montant si LIBELLE non listé
If .Cells(i, 1) = .Cells(i - 1, 1) Then .Cells(i - 1, col) = .Cells(i, col) 'si doublon
Next i
.RemoveDuplicates 1, Header:=xlNo 'élimine les doublons
End With
F.Cells(1).CurrentRegion.Borders.Weight = xlThin 'bordures
n = F.Cells(F.Rows.Count, 1).End(xlUp).Row - 2
F.Rows(n + 3 & ":" & F.Rows.Count).Delete 'RAZ en dessous
With F.UsedRange: End With 'actualise la barre de défilement verticale
'---remplissage du 2ème tableau---
colBudget = Application.Match("Budget", F.Rows(1), 0)
colRecap = Application.Match("RECAP*", F.Rows(1), 0)
F.Cells(2, colRecap + 1) = DateSerial(an, mois, 1)
F.Cells(2, colRecap + 2) = DateSerial(an - 1, mois, 1)
F.Cells(3, colRecap).Resize(n) = F.Cells(3, colBudget + 11).Resize(n).Value
F.Cells(3, colRecap + 1).Resize(n) = F.Cells(3, col).Resize(n).Value
col = 0: col = Application.Match(an - 1, F.Rows(1), 0) + mois - 1
F.Cells(3, colRecap + 2).Resize(n) = F.Cells(3, col).Resize(n).Value
F.Cells(3, colRecap + 3).Resize(n) = "=RC[-3]-RC[-2]"
F.Cells(3, colRecap + 4).Resize(n) = "=IFERROR(RC[-3]/RC[-2]-1,"""")"
F.Cells(3, colRecap + 5).Resize(n) = "=IFERROR(RC[-4]/RC[-5],"""")"
F.Cells(3, colRecap + 3).Resize(n, 3) = F.Cells(3, colRecap + 3).Resize(n, 3).Value 'supprime les formules
F.Cells(3, colRecap).Resize(n, 6).Borders.Weight = xlThin 'bordures
End If
Next e
End Sub