XL 2016 Impression d'un rapport PDF depuis une URL avec VBA

Boostez vos compétences Excel avec notre communauté !

Rejoignez Excel Downloads, le rendez-vous des passionnés où l'entraide fait la force. Apprenez, échangez, progressez – et tout ça gratuitement ! 👉 Inscrivez-vous maintenant !

mrcooll

XLDnaute Nouveau
Bonjour,
J'utilise sur mon entreprise un SI Angular, j'ai des rapports PDF que je génère et que j'imprime quotidiennement, je veux créer un programme VBA qui a pour but d'imprimer l’ensemble de mes rapports, j'ai tenté ce programme mais ça ne marche pas

Module:

VB:
Option Explicit

Public 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

Public Declare Function GetDesktopWindow _
Lib "user32" () _
As Long

Public Const SW_HIDE As Long = 0
Public Const SW_NORMAL As Long = 1
Public Const SW_MAXIMIZE As Long = 3
Public Const SW_MINIMIZE As Long = 6

Public Function fnShellOperation(strFilePath As String, _
Optional strOperation As String, _
Optional nShowCmd As Double) As Long
Dim hWndDesk As Long

'// use the desktop as default ... you should use your App.handle

hWndDesk = GetDesktopWindow()
If Len(strOperation) = 0 Then strOperation = "Open"
If nShowCmd = Null Then nShowCmd = SW_MAXIMIZE
'// Failure when >0 or <=32
fnShellOperation = ShellExecute(hWndDesk, strOperation, strFilePath, 0, 0, nShowCmd)

If fnShellOperation <= 32 Then
MsgBox "Couldn't " & strOperation & " " & strFilePath & vbCrLf & vbCrLf & _
"Error:= " & fnShellErr(fnShellOperation)
End If
'// OK check IF there was an Association Error
If fnShellOperation = 31 Then

'// OK Ask user if they want to Open it using another program

If MsgBox(strOperation & " Using another Application", vbYesNo) = vbYes Then

Shell "rundll32.exe shell32.dll,OpenAs_RunDLL " & strFilePath, vbNormalFocus

End If

End If

End Function

 

'//---------------------------------------------------------------------------------------

'// Function : fnShellErr

'// DateTime : 20/09/03 20:50

'// Author : "Ivan F Moala"
'// Site : "http://www.xcelfiles.com"

'// Purpose :

'---------------------------------------------------------------------------------------

Public Function fnShellErr(Ret As Long) As String
Select Case Ret

'// Typical Errors

Case 0: fnShellErr = "The operating system is out of memory or resources."

Case Is = 2: fnShellErr = "The specified FILE was not found."

Case Is = 3: fnShellErr = "The specified PATH was not found."

Case Is = 5: fnShellErr = "The operating system denied access to the specified file."

Case Is = 8: fnShellErr = "There was not enough memory to complete the operation."

Case Is = 11: fnShellErr = "The .EXE file is invalid (non-Win32 .EXE or error in .EXE image)."
Case Is = 26: fnShellErr = "A sharing violation occurred."
Case Is = 27: fnShellErr = "The filename association is incomplete or invalid."
Case Is = 28: fnShellErr = "The DDE transaction could not be completed because the request timed out."
Case Is = 29: fnShellErr = "The DDE transaction failed."
Case Is = 30: fnShellErr = "The DDE transaction could not be completed because other DDE transactions were being processed."
Case Is = 31: fnShellErr = "There is no application associated with the given filename extension."
Case Is = 32: fnShellErr = "The specified dynamic-link library was not found."
Case Else: fnShellErr = "*UNDEFINED* Error"
End Select
End Function



Public Function ShellImprime(URL As String)

    ShellExecute 0, "print", URL, "", "", 0
End Function

Bouton :

Code:
Private Sub CommandButton1_Click()
    Dim Ret As Long, myPath As String
      
    myPath = "https://**********/api/reports?code=17&amp;entityId=&amp;currentUsername=********&amp;currentActelId=5811#page=1&amp;zoom=auto,0,-677"
    '// Substitute here your Doc full path
    Ret = fnShellOperation(myPath, "print", SW_MAXIMIZE)
End S


finalement j'ai le message d'erreur de la PJ


Environnement
- MS Office Pro plus 2016
- Windows 10
- SI sous Angular
-Accès avec login et mot de passe
 

Pièces jointes

  • 1.png
    1.png
    58 KB · Affichages: 16
Pb résolu, à priori c'est plus compliquer de s’appuyer seulement sur VBA, j'ai dû passer par un script Python + selenium firefox + geckodriver
Python:
# -*- coding: iso-8859-1 -*-

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import time

# Options du navigateur Firefox
options = Options()
options.headless = False  # Si vous souhaitez voir le navigateur en action
options.accept_insecure_certs = True

# Chemin du GeckoDriver (assurez-vous de remplacer le chemin par le vôtre)
gecko_driver_path = r'gecko_driver_path ici'

# URL du PDF à imprimer
pdf_url = "PDF URL ICI"

# Chemin de sortie pour le journal
log_path = r'Py log text file ici'

# Informations d'identification
username = "login"
password = "pass"

# Ajouter un message de journalisation pour signaler le début du script
with open(log_path, 'a') as log_file:
    log_file.write('Début du script.\n')

try:
    # Configurer le profil du navigateur pour accepter tous les certificats
    capabilities = DesiredCapabilities().FIREFOX
    capabilities['acceptInsecureCerts'] = True

    # Créer une instance du navigateur Firefox avec les nouvelles options
    driver = webdriver.Firefox(executable_path=gecko_driver_path, options=options, capabilities=capabilities)
    with open(log_path, 'a') as log_file:
        log_file.write('Ouverture du navigateur réussie.\n')

    # Ouvrir l'URL de connexion
    login_url = "Login URL Page ici"
    driver.get(login_url)
    with open(log_path, 'a') as log_file:
        log_file.write('Ouverture de l\'URL de connexion réussie.\n')

    # Remplir le formulaire de connexion en utilisant des sélecteurs CSS
    username_selector = "input#username"
    password_selector = "input#password"
    login_form_selector = "form#loginForm"

    # Ajouter des messages de débogage pour vérifier les sélecteurs
    print(f"Username selector: {username_selector}")
    print(f"Password selector: {password_selector}")
    print(f"Login form selector: {login_form_selector}")

    driver.find_element("css selector", username_selector).send_keys(username)
    driver.find_element("css selector", password_selector).send_keys(password)
    driver.find_element("css selector", login_form_selector).submit()

    # Attendre que la connexion soit établie (ajustez si nécessaire)
    time.sleep(5)

    # Ouvrir l'URL du PDF après la connexion
    driver.get(pdf_url)
    with open(log_path, 'a') as log_file:
        log_file.write('Ouverture de l\'URL PDF réussie après la connexion.\n')

    # Attente pour observer la page (ajustez si nécessaire)
    time.sleep(5)

    # Imprimer la page (vous devrez peut-être ajuster cette partie en fonction de votre configuration)
    driver.execute_script("window.print();")
    with open(log_path, 'a') as log_file:
        log_file.write('Impression de la page.\n')

    # Fermer le navigateur
    driver.quit()
    with open(log_path, 'a') as log_file:
        log_file.write('Fermeture du navigateur réussie.\n')

except Exception as e:
    # En cas d'erreur, enregistrer l'exception dans le journal
    with open(log_path, 'a') as log_file:
        log_file.write(f'Erreur : {str(e)}\n')

# Ajouter un message de journalisation pour signaler la fin du script
with open(log_path, 'a') as log_file:
    log_file.write('Fin du script.\n')

sur Excel :

VB:
Sub RunPythonScript()
    Dim pythonPath As String
    Dim scriptPath As String
    Dim cmd As String
    
    ' Chemin vers l'interpréteur Python
    pythonPath = "chemin\vers\python.exe"  ' Remplacez par le chemin de votre installation Python
    
    ' Chemin vers le script Python
    scriptPath = "chemin\vers\pdf.py"  ' Remplacez par le chemin de votre script Python
    
    ' Construire la commande à exécuter
    cmd = pythonPath & " " & scriptPath
    
    ' Exécuter la commande
    Shell cmd, vbNormalFocus
End Sub
 
- Navigue sans publicité
- Accède à Cléa, notre assistante IA experte Excel... et pas que...
- Profite de fonctionnalités exclusives
Ton soutien permet à Excel Downloads de rester 100% gratuit et de continuer à rassembler les passionnés d'Excel.
Je deviens Supporter XLD

Discussions similaires

Réponses
8
Affichages
905
Réponses
1
Affichages
1 K
Compte Supprimé 979
C
Réponses
1
Affichages
2 K
Retour