Option Explicit Private Const FEUILLE_SOURCE As String = "Ventes" Private Const PREFIXE_RAPPORT As String = "Com_" '========================================================= ' PROCÉDURE PRINCIPALE '========================================================= Public Sub ExporterVentesParCommercial() Dim wb As Workbook Dim wsSource As Worksheet Dim donneesVentes As Variant Dim commerciaux As Object Dim commercial As Variant Dim wsRapport As Worksheet Dim dossierSortie As String On Error GoTo GestionErreur Set wb = ThisWorkbook Set wsSource = wb.Worksheets(FEUILLE_SOURCE) dossierSortie = LireDossierSortie(wb) donneesVentes = LireDonneesVentes(wsSource) Set commerciaux = ListerCommerciaux(donneesVentes) Application.ScreenUpdating = False For Each commercial In commerciaux.Keys Set wsRapport = CreerFeuilleRapport(wb, CStr(commercial)) RemplirRapport wsRapport, donneesVentes, CStr(commercial) MettreEnFormeRapport wsRapport ExporterRapportPDF wsRapport, dossierSortie, CStr(commercial) Next commercial Application.ScreenUpdating = True MsgBox commerciaux.Count & " rapports de ventes exportés.", _ vbInformation, "Export terminé" Exit Sub GestionErreur: Application.ScreenUpdating = True MsgBox "L'export a échoué : " & Err.Description, _ vbCritical, "Erreur d'export" End Sub '========================================================= ' VÉRIFIER LE CLASSEUR ET LIRE LES DONNÉES '========================================================= Private Function LireDossierSortie(ByVal wb As Workbook) As String If Len(wb.Path) = 0 Then Err.Raise vbObjectError + 100, , _ "Enregistrez le classeur avant d'exporter les PDF." End If LireDossierSortie = wb.Path & Application.PathSeparator End Function Private Function LireDonneesVentes(ByVal ws As Worksheet) As Variant Dim derniereLigne As Long derniereLigne = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row If derniereLigne < 2 Then Err.Raise vbObjectError + 101, , _ "La feuille Ventes ne contient aucune donnée." End If LireDonneesVentes = ws.Range("A1:D" & derniereLigne).Value2 End Function '========================================================= ' LISTER LES COMMERCIAUX (SANS DOUBLON) '========================================================= Private Function ListerCommerciaux(ByVal donnees As Variant) As Object Dim commerciaux As Object Dim i As Long Dim nomCommercial As String Set commerciaux = CreateObject("Scripting.Dictionary") commerciaux.CompareMode = vbTextCompare For i = 2 To UBound(donnees, 1) If Not IsError(donnees(i, 2)) Then nomCommercial = Trim$(CStr(donnees(i, 2))) If Len(nomCommercial) > 0 Then If Not commerciaux.Exists(nomCommercial) Then commerciaux.Add nomCommercial, True End If End If End If Next i If commerciaux.Count = 0 Then Err.Raise vbObjectError + 102, , _ "Aucun commercial n'a été trouvé." End If Set ListerCommerciaux = commerciaux End Function '========================================================= ' CRÉER OU RÉUTILISER UNE FEUILLE DE RAPPORT '========================================================= Private Function CreerFeuilleRapport( _ ByVal wb As Workbook, _ ByVal nomCommercial As String) As Worksheet Dim ws As Worksheet Dim nomFeuille As String nomFeuille = NomFeuilleValide(PREFIXE_RAPPORT & nomCommercial) On Error Resume Next Set ws = wb.Worksheets(nomFeuille) On Error GoTo 0 If ws Is Nothing Then Set ws = wb.Worksheets.Add( _ After:=wb.Worksheets(wb.Worksheets.Count)) ws.Name = nomFeuille Else ws.Cells.Clear End If Set CreerFeuilleRapport = ws End Function '========================================================= ' COPIER LES VENTES ET AJOUTER LE TOTAL '========================================================= Private Sub RemplirRapport( _ ByVal ws As Worksheet, _ ByVal donnees As Variant, _ ByVal nomCommercial As String) Dim i As Long Dim ligneSortie As Long Dim ligneTotal As Long ws.Range("A1:D1").Value = _ Array("Date", "Commercial", "Client", "Montant") ligneSortie = 2 For i = 2 To UBound(donnees, 1) If Not IsError(donnees(i, 2)) Then If StrComp(Trim$(CStr(donnees(i, 2))), _ nomCommercial, vbTextCompare) = 0 Then ws.Cells(ligneSortie, 1).Resize(1, 4).Value = _ Array(donnees(i, 1), donnees(i, 2), _ donnees(i, 3), donnees(i, 4)) ligneSortie = ligneSortie + 1 End If End If Next i ligneTotal = ligneSortie + 1 ws.Cells(ligneTotal, 3).Value = "TOTAL" ws.Cells(ligneTotal, 4).Formula = _ "=SUM(D2:D" & ligneSortie - 1 & ")" End Sub '========================================================= ' METTRE EN FORME LE RAPPORT '========================================================= Private Sub MettreEnFormeRapport(ByVal ws As Worksheet) Dim derniereLigneDonnees As Long Dim ligneTotal As Long Dim tbl As ListObject ligneTotal = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row derniereLigneDonnees = ligneTotal - 2 Set tbl = ws.ListObjects.Add( _ xlSrcRange, ws.Range("A1:D" & derniereLigneDonnees), , xlYes) tbl.TableStyle = "TableStyleMedium2" With ws.Range("C" & ligneTotal & ":D" & ligneTotal) .Font.Bold = True .Interior.Color = RGB(221, 235, 247) .Borders(xlEdgeTop).LineStyle = xlContinuous .Borders(xlEdgeTop).Weight = xlMedium End With ws.Columns("A").NumberFormat = "dd mmm yyyy" ws.Columns("D").NumberFormat = "#,##0.00" ws.Columns("A:D").AutoFit ParametrerImpression ws, ligneTotal End Sub '========================================================= ' PARAMÉTRER LA MISE EN PAGE DU PDF '========================================================= Private Sub ParametrerImpression( _ ByVal ws As Worksheet, _ ByVal ligneTotal As Long) With ws.PageSetup .PrintArea = ws.Range("A1:D" & ligneTotal).Address .Orientation = xlLandscape .PaperSize = xlPaperA4 .Zoom = False .FitToPagesWide = 1 .FitToPagesTall = False .CenterHorizontally = True .PrintTitleRows = "$1:$1" .LeftMargin = Application.InchesToPoints(0.3) .RightMargin = Application.InchesToPoints(0.3) .TopMargin = Application.InchesToPoints(0.5) .BottomMargin = Application.InchesToPoints(0.5) End With End Sub '========================================================= ' EXPORTER LA FEUILLE EN PDF '========================================================= Private Sub ExporterRapportPDF( _ ByVal ws As Worksheet, _ ByVal dossierSortie As String, _ ByVal nomCommercial As String) Dim cheminPDF As String cheminPDF = dossierSortie & _ NomFichierValide(nomCommercial) & "_Ventes.pdf" ws.ExportAsFixedFormat _ Type:=xlTypePDF, _ Filename:=cheminPDF, _ Quality:=xlQualityStandard, _ IncludeDocProperties:=True, _ IgnorePrintAreas:=False, _ OpenAfterPublish:=False End Sub '========================================================= ' NETTOYER LES NOMS DE FEUILLES '========================================================= Private Function NomFeuilleValide(ByVal valeur As String) As String Dim caracteresInterdits As Variant Dim car As Variant caracteresInterdits = Array("\", "/", ":", "*", "?", _ "[", "]") For Each car In caracteresInterdits valeur = Replace(valeur, CStr(car), "_") Next car NomFeuilleValide = Left$(valeur, 31) End Function '========================================================= ' NETTOYER LES NOMS DE FICHIERS PDF '========================================================= Private Function NomFichierValide(ByVal valeur As String) As String Dim caracteresInterdits As Variant Dim car As Variant caracteresInterdits = Array("\", "/", ":", "*", "?", _ """", "<", ">", "|") For Each car In caracteresInterdits valeur = Replace(valeur, CStr(car), "_") Next car NomFichierValide = Trim$(valeur) End Function