FAQ Excel

FAQ ExcelConsultez toutes les FAQ
Nombre d'auteurs : 46, nombre de questions : 845, dernière mise à jour : 30 mars 2022
Sommaire→Les impressions- Comment économiser le papier ?
- Comment lancer une impression par macro ?
- Comment utiliser l'aperçu avant impression par macro ?
- Comment imprimer la page active et les tous les classeurs liés ?
- Comment imprimer une Feuille en noir et blanc ?
- Comment utiliser les boîtes de dialogue intégrées pour imprimer et choisir l'imprimante ?
- Comment empêcher l'impression par macro ?
- Comment lister les imprimantes installées et préciser laquelle est active ?
- Comment récupérer les propriétés des imprimantes installées ?
- Comment récupérer les propriétés de la zone d'impression d'une imprimante (marges horizontales et verticales) ?
- Comment modifier la mise en page avant impression ?
- Comment imprimer un fichier texte ?
- Comment ouvrir le port d'impression pour éditer un texte ?
- Comment imprimer un UserForm ?
- Comment utiliser l'aperçu avant impression d'une feuille de calcul depuis un UserForm ?
- Comment répéter l'impression de lignes d'entête sur plusieurs pages ?
- Comment imprimer une sélection de feuilles ?
- Comment ajouter un numéro de page à l'impression ?
- Comment cacher le contenu de certaines cellules pour l'impression ?
- Comment imprimer un fichier pdf depuis Excel ?
- Comment retrouver le nombre de pages à imprimer dans la feuille active ?
- Comment obtenir un pied de page différent sur 1ère page ?
- Comment afficher le symbole ET Commercial (&) dans un en-tête ou pied de page Excel 2007 ?
Ce chapitre de la FAQ présente quelques exemples pour imprimer les classeurs. Lorsque vous faites des essais ou que vous souhaitez
simplement avoir une idée du résultat de votre travail, utilisez l'option d'aperçu avant impression. Vous économiserez ainsi de l'encre,
du papier et du temps.
Plus généralement, il faut toujours avoir une réflexion sur l'utilisation du papier pour ne pas le gaspiller.
Pour imprimer le classeur, utilisez :
ThisWorkbook.PrintOut'spécifiez l'argument "Copies" pour définir le nombre de copies (3 dans cet exemple).
ActiveWorkbook.PrintOut Copies:=3, Collate:=TruePour imprimer une feuille spécifique :
Worksheets("Feuil2").PrintOutpour imprimer une plage de cellules :
Worksheets("Feuil1").Range("A1:D10").printOutPour effectuer un aperçu de la Feuille nommée "Feuil2", utilisez la méthode PrintPreview :
Worksheets("Feuil2").PrintPreviewVous pouvez aussi effectuer l'aperçu avant impression en utilisant les boîtes de dialogues intégrées d'Excel:
Application.Dialogs(xlDialogPrintPreview).Show
Remarque :
L'argument False permet de rendre inactifs les boutons "Mise en page" et "Marges".
Application.Dialogs(xlDialogPrintPreview).Show False
Cette macro boucle sur les liens de la feuille active et ouvre le fichier lié s'il s'agit d'un classeur.
Chaque feuille de ce classeur est ensuite imprimée.
Sub imprimerPageActiveEt_Liensclasseurs()
Dim Lien As Hyperlink
Dim I As Byte
Application.ScreenUpdating = False
'Imprime la feuille active
ActiveSheet.PrintOut
'Boucle sur les liens de la feuille active
For Each Lien In ActiveSheet.Hyperlinks
'Vérifie si le lien correspond à un classeur
If Right(Range(Lien.Range.Address).Hyperlinks(1).Address, 4) = ".xls" Then
'Déclenche le lien pour ouvrir le classeur
Range(Lien.Range.Address).Hyperlinks(1).Follow NewWindow:=False
'Imprime le classeur
ActiveWorkbook.PrintOut
'Referme le classeur
ActiveWorkbook.Close
End If
Next
Application.ScreenUpdating = True
End SubSub impressionNoirEtBlanc()
With Worksheets("Feuil1")
.PageSetup.BlackAndWhite = True 'paramétrage N&B
.PrintOut 'imprime
.PageSetup.BlackAndWhite = False 'réinitialisation
End With
End SubLa procédure suivante affiche la boîte de dialogue d'impression, en précisant le nombre de copies par défaut (3).
Application.Dialogs(xlDialogPrint).Show , , , 3Cet autre exemple affiche la boîte de dialogue permettant de choisir l'imprimante pour l'édition :
If Application.Dialogs(xlDialogPrinterSetup).Show = True Then Feuil1.printOutSi les macros sont activées dans le classeur, vous pouvez utiliser l'évènement Workbook_BeforePrint.
Private Sub Workbook_BeforePrint(Cancel As Boolean)
Cancel = True
End SubCet évènement survient avant l'impression. L'impression commence uniquement à l'issue de cette procédure.
Le paramètre Cancel = True bloque toute impression.
Sub listeImprimantes_et_Statut()
'testé avec Excel 2002 et WinXP
Dim objWMIService As Object, colInstalledPrinters As Object, objPrinter As Object
Dim nomPC As String, Resultat As String
nomPC = "."
Set objWMIService = GetObject("winmgmts:" & _
"{impersonationLevel=impersonate}!\\" & nomPC & "\root\cimv2")
Set colInstalledPrinters = objWMIService.execQuery("Select * from Win32_Printer")
For Each objPrinter In colInstalledPrinters
Resultat = Resultat & objPrinter.Name & " imprimante active : " & objPrinter.Default & vbLf
Next
MsgBox Resultat
End SubSub ProprietesImprimantes()
Dim objWMIService As Object, colItems As Object
Dim objItem As Object
Dim strComputer As String
Dim i As Byte
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.execQuery("Select * from Win32_printerConfiguration", , 48)
For Each objItem In colItems
i = i + 1
Cells(1, i) = "bitsPerPel: " & objItem.bitsPerPel
Cells(2, i) = "Caption: " & objItem.Caption
Cells(3, i) = "Collate: " & objItem.Collate
Cells(4, i) = "Color: " & objItem.Color
Cells(5, i) = "Copies: " & objItem.Copies
Cells(6, i) = "Description: " & objItem.Description
Cells(7, i) = "deviceName: " & objItem.deviceName
Cells(8, i) = "displayFlags: " & objItem.displayFlags
Cells(9, i) = "displayFrequency: " & objItem.displayFrequency
Cells(10, i) = "ditherType: " & objItem.ditherType
Cells(11, i) = "driverVersion: " & objItem.driverVersion
Cells(12, i) = "Duplex: " & objItem.Duplex
Cells(13, i) = "formName: " & objItem.formName
Cells(14, i) = "horizontalResolution: " & objItem.horizontalResolution
Cells(15, i) = "ICMIntent: " & objItem.ICMIntent
Cells(16, i) = "ICMMethod: " & objItem.ICMMethod
Cells(17, i) = "logPixels: " & objItem.logPixels
Cells(18, i) = "mediaType: " & objItem.mediaType
Cells(19, i) = "Name: " & objItem.Name
Cells(20, i) = "Orientation: " & objItem.Orientation
Cells(21, i) = "paperLength: " & objItem.paperLength
Cells(22, i) = "paperSize: " & objItem.PaperSize
Cells(23, i) = "paperWidth: " & objItem.paperWidth
Cells(24, i) = "pelsHeight: " & objItem.pelsHeight
Cells(25, i) = "pelsWidth: " & objItem.pelsWidth
Cells(26, i) = "printQuality: " & objItem.PrintQuality
Cells(27, i) = "Scale: " & objItem.Scale
Cells(28, i) = "SettingID: " & objItem.SettingID
Cells(29, i) = "specificationVersion: " & objItem.specificationVersion
Cells(30, i) = "TTOption: " & objItem.TTOption
Cells(31, i) = "verticalResolution: " & objItem.verticalResolution
Cells(32, i) = "XResolution: " & objItem.Xresolution
Cells(33, i) = "YResolution: " & objItem.Yresolution
Columns(i).AutoFit
Next
End SubCette autre adaptation permet de vérifier si l'imprimante est paramétrée pour imprimer en couleur ou en noir et blanc.
Sub verifier_parametre_Couleur_NB_Imprimante_V02()
Dim objWMIService As Object, colItems As Object
Dim objItem As Object
Dim strComputer As String
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.execQuery("Select * from Win32_printerConfiguration", , 48)
For Each objItem In colItems
Select Case objItem.Color
Case 1: MsgBox objItem.Name & " : 'noir et blanc'"
Case 2: MsgBox objItem.Name & " : 'couleur'"
End Select
Next
End SubOption Explicit
Declare Function CreateDC Lib "gdi32" Alias "CreateDCA" _
(ByVal lpDriverName As String, ByVal lpDeviceName As String, _
ByVal lpOutput As Long, ByVal lpInitData As Long) As Long
Declare Function GetDeviceCaps Lib "gdi32" _
(ByVal hdc As Long, ByVal nIndex As Long) As Long
Const HORZRES = 8
Const VERTRES = 10
Const LOGPIXELSX = 88
Const LOGPIXELSY = 90
Const PHYSICALWIDTH = 110
Const PHYSICALHEIGHT = 111
Const PHYSICALOFFSETX = 112
Const PHYSICALOFFSETY = 113
Sub ProprietesZoneImpressionImprimante()
'source http://support.microsoft.com/?id=193943
Dim dpiX As Long, dpiY As Long
Dim MarginLeft As Long, MarginRight As Long
Dim MarginTop As Long, MarginBottom As Long
Dim PrintAreaHorz As Long, PrintAreaVert As Long
Dim PhysHeight As Long, PhysWidth As Long
Dim Info As String, Cible As String
Dim HwndPrint As Long
'--- Attention à bien indiquer le nom de l'imprimante avant de lancer la macro ---
'
Cible = "hp deskjet 940c" 'Nom de l'imprimante
'
'
HwndPrint = CreateDC(0, Cible, 0, 0)
dpiX = GetDeviceCaps(HwndPrint, LOGPIXELSX)
Info = "Pixels X: " & dpiX & " dpi"
dpiY = GetDeviceCaps(HwndPrint, LOGPIXELSY)
Info = Info & vbCrLf & "Pixels Y: " & dpiY & " dpi"
MarginLeft = GetDeviceCaps(HwndPrint, PHYSICALOFFSETX)
Info = Info & vbCrLf & "Unprintable space on left: " & _
MarginLeft & " pixels (" & Format(MarginLeft / dpiX, "0.000") & " inches)"
MarginTop = GetDeviceCaps(HwndPrint, PHYSICALOFFSETY)
Info = Info & vbCrLf & "Unprintable space on top: " & _
MarginTop & " pixels (" & Format(MarginTop / dpiY, "0.000") & " inches)"
PrintAreaHorz = GetDeviceCaps(HwndPrint, HORZRES)
Info = Info & vbCrLf & "Printable space (Horizontal): " & _
PrintAreaHorz & " pixels (" & Format(PrintAreaHorz / dpiX, "0.000") & " inches)"
PrintAreaVert = GetDeviceCaps(HwndPrint, VERTRES)
Info = Info & vbCrLf & "Printable space (Vertical): " & _
PrintAreaVert & " pixels (" & Format(PrintAreaVert / dpiY, "0.000") & " inches)"
PhysWidth = GetDeviceCaps(HwndPrint, PHYSICALWIDTH)
Info = Info & vbCrLf & "Total space (Horizontal): " & _
PhysWidth & " pixels (" & Format(PhysWidth / dpiX, "0.000") & " inches)"
MarginRight = PhysWidth - PrintAreaHorz - MarginLeft
Info = Info & vbCrLf & "Unprintable space on right: " & _
MarginRight & " pixels (" & Format(MarginRight / dpiX, "0.000") & " inches)"
PhysHeight = GetDeviceCaps(HwndPrint, PHYSICALHEIGHT)
Info = Info & vbCrLf & "Total space (Vertical): " & _
PhysHeight & " pixels (" & Format(PhysHeight / dpiY, "0.000") & " inches)"
MarginBottom = PhysHeight - PrintAreaVert - MarginTop
Info = Info & vbCrLf & "Unprintable space on bottom: " & _
MarginBottom & " pixels (" & Format(MarginBottom / dpiY, "0.000") & " inches)"
MsgBox Info, , "Information"
End SubCet exemple modifie la zone d'impression et les marges dans la feuille.
Sub miseEnPageAvantImpression()
With Feuil1.PageSetup
'Définit la zone d'impression pour une plage de cellules.
.PrintArea = "$A$1:$E$10"
'Mise en page: définit les marges
.LeftMargin = Application.InchesToPoints(0.5)
.RightMargin = Application.InchesToPoints(0.75)
.TopMargin = Application.InchesToPoints(1.5)
.BottomMargin = Application.InchesToPoints(1)
.HeaderMargin = Application.InchesToPoints(0.5)
.FooterMargin = Application.InchesToPoints(0.5)
End With
Feuil1.PrintPreview
End SubIl est aussi possible d'adapter la zone d'impression à une seule feuille pour une économie de papier :
With Feuil1.PageSetup
.PrintArea = "A1:M100"
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
End WithVous pouvez réinitialiser la zone d'impression à la feuille complète ainsi :
Feuil1.PageSetup.PrintArea = ""Une autre solution :
Feuil1.PageSetup.PrintArea = FalsePour centrer le contenu de la feuille lors de l'impression, utilisez :
With Feuil1
.PageSetup.CenterHorizontally = True
.PageSetup.CenterVertically = True
.PrintOut
End WithCe dernier exemple comment imprimer la première page en mode Paysage et la deuxième page en mode Portrait.
With Feuil1
.PageSetup.Orientation = xlLandscape
.PrintOut From:=1, To:=1
.PageSetup.Orientation = xlPortrait
.PrintOut From:=2, To:=2
End WithShell "notepad.exe /P""C:\monRepertoire\leFichier.txt""", 1Sub imprimerTexte()
Open "LPT1:" For Output As #1
Print #1, "Test d'impression."
Print #1, "Test 2eme ligne."
Close #1
End SubPrivate Sub CommandButton1_Click()
Me.PrintForm
End SubL'image du UserForm est automatiquement placée dans le coin supérieur gauche de la page imprimée.
Il n'existe pas d'option pour centrer ou repositionner l'impression. La seule solution palliative consiste à faire une copie d'écran de la boîte de dialogue. Ensuite vous faites un collage dans la feuille de calcul en tant qu'image, pour la manipuler à votre guise.
Cet exemple imprime l'UserForm centré dans la page :
Option Explicit
Private Declare Sub keybd_event Lib "user32" ( _
ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, _
ByVal dwExtraInfo As Long)
Private Sub CommandButton1_Click()
Dim Ws As Worksheet
'Copie d'écran de la forme active
keybd_event vbKeySnapshot, 1, 0&, 0&
DoEvents
'Ajoute une feuille pour coller l'image de la forme
Set Ws = Sheets.Add
Ws.Paste
'impression centrée dans la page
With Ws
.PageSetup.CenterHorizontally = True
.PageSetup.CenterVertically = True
.PrintOut
End With
End SubPrivate Sub CommandButton1_Click()
Me.Hide
'Aperçu avant impression de la Feuil1
Feuil1.PrintPreview
Me.Show
End SubLorsque vous imprimez un onglet dont les données se suivent sur plusieurs pages verticales, il est possible de répéter l'impression des premières lignes d'entête dans chaque page. Cela facilite ensuite la relecture du document.
Si par exemple vous souhaitez répéter l'impression des 4 premières lignes dans chaque page :
Menu Fichier
Mise en page
Onglet "Feuille"
Dans le champ "Lignes à répéter en haut", Sélectionnez les 4 lignes qui devront apparaître sur chaque page imprimée.
Vous pouvez aussi saisir directement $1:$4 dans ce champ.
Cliquez sur le bouton OK pour valider.
Cette propriété fonctionne aussi pour répéter l'impression de colonnes.
Vous pouvez spécifier le nom des feuilles à imprimer dans un tableau Array().
'Imprime une sélection de feuilles ("Feuil1" et "Feuil3")
Worksheets(Array("Feuil1", "Feuil3")).PrintOut
La gestion de la mise en page de votre feuille pour l'impression passe par l'intermédiaire de la propriété PageSetup.
Celle-ci renvoie un objet PageSetup qu'il faut manipuler.
Par exemple :
With objFeuille.PageSetup
.CenterFooter = "&P"
.CenterHeader = "&F"
.FirstPageNumber = 3
.FitToPagesWide = 1
.Orientation = xlLandscape
.PrintGridlines = False
.PrintHeadings = False
End With
objFeuille.PrintOut 1, 1, 1, FalseCe code imprime la feuille en mettant le nom du fichier dans l'en-tête, le numéro de page dans le pied, celui-ci commençant à 3, force l'impression sur une page en largeur en mode paysage. Ni les lignes, ni les numéros de lignes/colonnes ne seront imprimés.
Option Explicit
Option Base 1
Sub Test()
'Worksheets(1) définit la premiere feuille du classeur, à imprimer.
'Range("C4:F15")définit la plage de cellules à masquer
MasqueContenuCell_Print Worksheets(1), Range("C4:F15")
End Sub
Sub MasqueContenuCell_Print(Feuille As Worksheet, Plage As Range)
Dim FormatInit() As Variant
Dim Cell As Range
Dim i As Integer
'Redimesionne le tableau qui va stocker les formats initiaux
ReDim Preserve FormatInit(Plage.Cells.Count)
'Boucle sur la plage de cellules
For Each Cell In Plage
i = i + 1
FormatInit(i) = Cell.NumberFormat
Next Cell
'Applique le format ;;; pour masquer le contenu des cellules.
Plage.NumberFormat = ";;;"
'Feuille.PrintPreview
Feuille.PrintOut
i = 0
'Boucle sur la plage de cellules pour réattibuer les formats initiaux
For Each Cell In Plage
i = i + 1
Cell.NumberFormat = FormatInit(i)
Next Cell
End SubCette méthode fonctionne aussi pour d'autres formats de fichiers.
Option Explicit
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
(ByVal hWnd As Long, ByVal lpOperation As String, ByVal lpFile As String _
, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
Sub ImprimerFichier()
Dim NomFichier As String
Dim x As Long
x = FindWindow("XLMAIN", Application.Caption)
NomFichier = "C:\dossier\rapport.pdf"
ShellExecute x, "print", NomFichier, "", "", 1
End SubEn utilisant les anciennes fonctions ExecuteExcel4Macro, il est possible d'identifier le nombre total de pages qui seront imprimées dans la feuille active.
MsgBox ExecuteExcel4Macro("GET.DOCUMENT(50)")
Cette solution, par macro, personnalise le pied de page central et lance l'impression.
La première page va contenir le texte ""Pied de page 1"". Les autres pages contiendront le texte "Pieds de Pages suivants".
With Feuil1
.PageSetup.CenterFooter = "Pied de page 1"
.PrintOut From:=1, To:=1 ', preview:=True
.PageSetup.CenterFooter = "Pieds de Pages suivants"
.PrintOut From:=2, To:=ExecuteExcel4Macro("GET.DOCUMENT(50)") ', preview:=True
End WithSaisissez le symbole deux fois pour que celui-ci soit visible dans l'en-tête ou le pied de page :
Nitro && Glycérine.



