VBA : Print CSV file as XLSX

I am trying to print a CSV file to look like a XLSX file. What I mean by that is that when I currently print I see :

Current CSV

and what I would like is:

Desired CSV

I already have 2 scripts:

Outlook Session:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Private Sub Application_NewMailEx(ByVal EntryIDCollection As String)
Dim objNamespace As Outlook.NameSpace
Dim objMail As Object ' Utilisation de Object pour capturer tout type d'élément
Dim objAttachments As Outlook.Attachments
Dim objAttachment As Outlook.attachment
Dim entryID As String
Dim entryIDs() As String
Dim i As Long
Dim tempFolder As String
Dim filePath As String
' Dossier temporaire pour enregistrer les fichiers
tempFolder = "C:temp"
' Assurez-vous que le dossier existe
If Dir(tempFolder, vbDirectory) = "" Then
MkDir tempFolder
End If
' Obtenir le Namespace d'Outlook
Set objNamespace = Application.GetNamespace("MAPI")
' Diviser la chaîne EntryIDCollection en cas de réception de plusieurs emails
entryIDs = Split(EntryIDCollection, ",")
' Boucle sur chaque email reçu
For i = LBound(entryIDs) To UBound(entryIDs)
entryID = entryIDs(i)
On Error Resume Next
' Essayer de récupérer l'élément comme MailItem
Set objMail = objNamespace.GetItemFromID(entryID)
On Error GoTo 0
' Vérifier si l'objet a été récupéré correctement
If Not objMail Is Nothing Then
' Vérifier si c'est bien un MailItem
If TypeOf objMail Is Outlook.mailItem Then
' Vérifier si l'objet du mail contient le texte désiré (utilisation de InStr pour plus de flexibilité)
If InStr(1, Trim(LCase(objMail.Subject)), "People on site", vbTextCompare) > 0 Then
' Obtenir les pièces jointes
Set objAttachments = objMail.Attachments
' Boucle à travers les pièces jointes
For Each objAttachment In objAttachments
' Vérifier si la pièce jointe est un CSV
If LCase(Right(objAttachment.FileName, 3)) = "csv" Then
' Chemin du fichier temporaire
filePath = tempFolder & objAttachment.FileName
' Enregistrer la pièce jointe
objAttachment.SaveAsFile filePath
' Appel à la fonction d'impression (assure-toi que cette fonction est définie)
PrintCSVOnMultiplePrinters filePath
' Supprimer le fichier après impression
Kill filePath
End If
Next objAttachment
End If
End If
Else
Debug.Print "Erreur : Impossible de récupérer l'élément avec ID " & entryID
End If
Next i
' Libération des objets
Set objNamespace = Nothing
Set objMail = Nothing
Set objAttachments = Nothing
End Sub
</code>
<code>Private Sub Application_NewMailEx(ByVal EntryIDCollection As String) Dim objNamespace As Outlook.NameSpace Dim objMail As Object ' Utilisation de Object pour capturer tout type d'élément Dim objAttachments As Outlook.Attachments Dim objAttachment As Outlook.attachment Dim entryID As String Dim entryIDs() As String Dim i As Long Dim tempFolder As String Dim filePath As String ' Dossier temporaire pour enregistrer les fichiers tempFolder = "C:temp" ' Assurez-vous que le dossier existe If Dir(tempFolder, vbDirectory) = "" Then MkDir tempFolder End If ' Obtenir le Namespace d'Outlook Set objNamespace = Application.GetNamespace("MAPI") ' Diviser la chaîne EntryIDCollection en cas de réception de plusieurs emails entryIDs = Split(EntryIDCollection, ",") ' Boucle sur chaque email reçu For i = LBound(entryIDs) To UBound(entryIDs) entryID = entryIDs(i) On Error Resume Next ' Essayer de récupérer l'élément comme MailItem Set objMail = objNamespace.GetItemFromID(entryID) On Error GoTo 0 ' Vérifier si l'objet a été récupéré correctement If Not objMail Is Nothing Then ' Vérifier si c'est bien un MailItem If TypeOf objMail Is Outlook.mailItem Then ' Vérifier si l'objet du mail contient le texte désiré (utilisation de InStr pour plus de flexibilité) If InStr(1, Trim(LCase(objMail.Subject)), "People on site", vbTextCompare) > 0 Then ' Obtenir les pièces jointes Set objAttachments = objMail.Attachments ' Boucle à travers les pièces jointes For Each objAttachment In objAttachments ' Vérifier si la pièce jointe est un CSV If LCase(Right(objAttachment.FileName, 3)) = "csv" Then ' Chemin du fichier temporaire filePath = tempFolder & objAttachment.FileName ' Enregistrer la pièce jointe objAttachment.SaveAsFile filePath ' Appel à la fonction d'impression (assure-toi que cette fonction est définie) PrintCSVOnMultiplePrinters filePath ' Supprimer le fichier après impression Kill filePath End If Next objAttachment End If End If Else Debug.Print "Erreur : Impossible de récupérer l'élément avec ID " & entryID End If Next i ' Libération des objets Set objNamespace = Nothing Set objMail = Nothing Set objAttachments = Nothing End Sub </code>
Private Sub Application_NewMailEx(ByVal EntryIDCollection As String)
    Dim objNamespace As Outlook.NameSpace
    Dim objMail As Object ' Utilisation de Object pour capturer tout type d'élément
    Dim objAttachments As Outlook.Attachments
    Dim objAttachment As Outlook.attachment
    Dim entryID As String
    Dim entryIDs() As String
    Dim i As Long
    Dim tempFolder As String
    Dim filePath As String
    
    ' Dossier temporaire pour enregistrer les fichiers
    tempFolder = "C:temp"
    
    ' Assurez-vous que le dossier existe
    If Dir(tempFolder, vbDirectory) = "" Then
        MkDir tempFolder
    End If
    
    ' Obtenir le Namespace d'Outlook
    Set objNamespace = Application.GetNamespace("MAPI")
    
    ' Diviser la chaîne EntryIDCollection en cas de réception de plusieurs emails
    entryIDs = Split(EntryIDCollection, ",")
    
    ' Boucle sur chaque email reçu
    For i = LBound(entryIDs) To UBound(entryIDs)
        entryID = entryIDs(i)
        
        On Error Resume Next
        ' Essayer de récupérer l'élément comme MailItem
        Set objMail = objNamespace.GetItemFromID(entryID)
        On Error GoTo 0
        
        ' Vérifier si l'objet a été récupéré correctement
        If Not objMail Is Nothing Then
            ' Vérifier si c'est bien un MailItem
            If TypeOf objMail Is Outlook.mailItem Then
                ' Vérifier si l'objet du mail contient le texte désiré (utilisation de InStr pour plus de flexibilité)
                If InStr(1, Trim(LCase(objMail.Subject)), "People on site", vbTextCompare) > 0 Then
                    
                    ' Obtenir les pièces jointes
                    Set objAttachments = objMail.Attachments
                    
                    ' Boucle à travers les pièces jointes
                    For Each objAttachment In objAttachments
                        ' Vérifier si la pièce jointe est un CSV
                        If LCase(Right(objAttachment.FileName, 3)) = "csv" Then
                            ' Chemin du fichier temporaire
                            filePath = tempFolder & objAttachment.FileName
                            
                            ' Enregistrer la pièce jointe
                            objAttachment.SaveAsFile filePath
                            
                            ' Appel à la fonction d'impression (assure-toi que cette fonction est définie)
                            PrintCSVOnMultiplePrinters filePath
                            
                            ' Supprimer le fichier après impression
                            Kill filePath
                        End If
                    Next objAttachment
                End If
            End If
        Else
            Debug.Print "Erreur : Impossible de récupérer l'élément avec ID " & entryID
        End If
    Next i
    
    ' Libération des objets
    Set objNamespace = Nothing
    Set objMail = Nothing
    Set objAttachments = Nothing
End Sub

Module1 :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Declare PtrSafe Function SetDefaultPrinter Lib "winspool.drv" Alias "SetDefaultPrinterA" (ByVal printerName As String) As Long
Sub PrintCSVOnMultiplePrinters(filePath As String)
Dim xlApp As Object
Dim xlBook As Object
Dim xlSheet As Object
Dim currentPrinter As String
' Créer une instance de l'application Excel
Set xlApp = CreateObject("Excel.Application")
' Ouvrir le fichier CSV
Set xlBook = xlApp.Workbooks.Open(filePath, False, True)
' Sélectionner la feuille active
Set xlSheet = xlBook.Sheets(1)
' Sauvegarder l'imprimante par défaut actuelle
currentPrinter = xlApp.ActivePrinter
' Imprimer sur la première imprimante (PEY01) en définissant l'imprimante par défaut
Call SetDefaultPrinter("\PRINTSRV01PEY01")
xlSheet.PrintOut Copies:=1, Collate:=True, IgnorePrintAreas:=False
' Imprimer sur la deuxième imprimante (PEY05) en définissant l'imprimante par défaut
Call SetDefaultPrinter("\PRINTSRV01PEY05")
xlSheet.PrintOut Copies:=1, Collate:=True, IgnorePrintAreas:=False
' Restaurer l'imprimante par défaut précédente
Call SetDefaultPrinter(currentPrinter)
' Fermer le fichier sans sauvegarder
xlBook.Close False
xlApp.Quit
' Libérer la mémoire
Set xlSheet = Nothing
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
</code>
<code>Declare PtrSafe Function SetDefaultPrinter Lib "winspool.drv" Alias "SetDefaultPrinterA" (ByVal printerName As String) As Long Sub PrintCSVOnMultiplePrinters(filePath As String) Dim xlApp As Object Dim xlBook As Object Dim xlSheet As Object Dim currentPrinter As String ' Créer une instance de l'application Excel Set xlApp = CreateObject("Excel.Application") ' Ouvrir le fichier CSV Set xlBook = xlApp.Workbooks.Open(filePath, False, True) ' Sélectionner la feuille active Set xlSheet = xlBook.Sheets(1) ' Sauvegarder l'imprimante par défaut actuelle currentPrinter = xlApp.ActivePrinter ' Imprimer sur la première imprimante (PEY01) en définissant l'imprimante par défaut Call SetDefaultPrinter("\PRINTSRV01PEY01") xlSheet.PrintOut Copies:=1, Collate:=True, IgnorePrintAreas:=False ' Imprimer sur la deuxième imprimante (PEY05) en définissant l'imprimante par défaut Call SetDefaultPrinter("\PRINTSRV01PEY05") xlSheet.PrintOut Copies:=1, Collate:=True, IgnorePrintAreas:=False ' Restaurer l'imprimante par défaut précédente Call SetDefaultPrinter(currentPrinter) ' Fermer le fichier sans sauvegarder xlBook.Close False xlApp.Quit ' Libérer la mémoire Set xlSheet = Nothing Set xlBook = Nothing Set xlApp = Nothing End Sub </code>
Declare PtrSafe Function SetDefaultPrinter Lib "winspool.drv" Alias "SetDefaultPrinterA" (ByVal printerName As String) As Long


Sub PrintCSVOnMultiplePrinters(filePath As String)
    Dim xlApp As Object
    Dim xlBook As Object
    Dim xlSheet As Object
    Dim currentPrinter As String

    ' Créer une instance de l'application Excel
    Set xlApp = CreateObject("Excel.Application")

    ' Ouvrir le fichier CSV
    Set xlBook = xlApp.Workbooks.Open(filePath, False, True)
    
    ' Sélectionner la feuille active
    Set xlSheet = xlBook.Sheets(1)
    
    ' Sauvegarder l'imprimante par défaut actuelle
    currentPrinter = xlApp.ActivePrinter
    
    ' Imprimer sur la première imprimante (PEY01) en définissant l'imprimante par défaut
    Call SetDefaultPrinter("\PRINTSRV01PEY01")
    xlSheet.PrintOut Copies:=1, Collate:=True, IgnorePrintAreas:=False
    
    ' Imprimer sur la deuxième imprimante (PEY05) en définissant l'imprimante par défaut
    Call SetDefaultPrinter("\PRINTSRV01PEY05")
    xlSheet.PrintOut Copies:=1, Collate:=True, IgnorePrintAreas:=False
    
    ' Restaurer l'imprimante par défaut précédente
    Call SetDefaultPrinter(currentPrinter)
    
    ' Fermer le fichier sans sauvegarder
    xlBook.Close False
    xlApp.Quit
    
    ' Libérer la mémoire
    Set xlSheet = Nothing
    Set xlBook = Nothing
    Set xlApp = Nothing
End Sub

As you can see, there’s 1 script that switches printers and the other that detects the incoming mail containing the CSV and prints it.

New contributor

Gamix is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

6

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật