XL 2016 VBA - Récupérer le texte d'un fichier PDF

Dudu2

XLDnaute Barbatruc
Bonjour,

Y a-t-il un moyen de chercher et récupérer du texte directement dans un PDF sans avoir à l'ouvrir / tout sélectionner / copier dans le clipboard texte ?

Merci pour toute information.

Edit: Titre modifié pour mieux refléter la solution de cette longue discussion.
 
Dernière édition:

Dudu2

XLDnaute Barbatruc
Ok, moi je ne trouve pas pourquoi un simple FindWindow après le Shell empêche les SendKeys de fonctionner. Ça me dépasse complètement et je ne trouve pas de solution.
Même avec des SetForegroundWindow et autres trucs. Je vais finir par adopter ta solution.
 

patricktoulon

XLDnaute Barbatruc
pourquoi crois tu que je n'ai pas pris ce chemin ? ;)
il est vrai que ce problème est plus present dans les version 64 mais bon

donc voila la version 2 avec l'api keybd_event pour les touches
et je n'ai plus mon pavé déactivé
testé 20 fois d'affilé 20 réussites

le principe
1°on vide le clipboard
2° on cherche le browser dans le case
3°on shel le browser dans un newindows avec l'url du fichier
4°on attent pas que le document soit completement chargé mais on attend simplement que le hdc de la fenêtre soit en memoire
en gros (que la fenêtre existe )
et pour ça une seconde suffit



5 apres c'est simple
on mitraille la fenêtre de ctrl+a+c tant que le clipboard n'est pas plein
6° on ferme le browser
puis return sur worksheet

terminé
VB:
Option Explicit
Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Declare PtrSafe Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
'-----------------------------------------
'Open a PDF and copy the text in the sheet
'Autor:[@Dudu2] on exceldownloads
'code redesigned by [@patricktoulon] on exceldownloads
'adding Chrome firefox control in an select case
'reduction of (window ready wait times) for  (chrome or firefox)
'added clipboard management
'non-empty clipboard wait loop
'loading time lasts the time the clipboard takes to load the data
'updated V 2
'replacing wscript.shell.sendkeys
'by simulating keys with Api keybd_event
'the numeric keypad is no longer disabled
'-----------------------------------------
Function GetPDFTextViaExcel(FichierPDF As String) As String
    Dim nav$, T$, clip As Object, wshshell As Object

    Cells(1, 1).CurrentRegion.ClearContents
    'browser path constantes
    Const nav1 = "C:\Program Files\Google\Chrome\Application\chrome.exe"
    Const nav2 = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
    Const nav3 = "C:\Program Files\Mozilla Firefox\firefox.exe"
    Const nav4 = "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"

    'select case true to find the browser installed on your system
    Select Case True
    Case Dir(nav3) <> "": nav = nav3    'je met le nav3 en premier je préfère firefox64
    Case Dir(nav1) <> "": nav = nav1
    Case Dir(nav2) <> "": nav = nav2
    Case Dir(nav4) <> "": nav = nav4
    Case Else
    End Select

    'we create the clipboard object (late binding)no reference required
    ' we empty the clipboard
    Set clip = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
    clip.SetText "": clip.PutInClipboard

    'run the browser chosen in the select case
    Call Shell(nav & " --new-window -url " & """" & FichierPDF & """", vbNormalFocus)

    'we still leave a minimum of 1 second for the window to be ready
    'even if the document is not completely loaded
    Sleep 1000

    'creating the wscript.shell object(no reference required)
    'Set wshshell = CreateObject("wscript.shell")


    'loop and  simulating (CTRL+A and C keys) as long as the clipboard is not full
    Do While Len(T) = 0
        keybd_event &H11, 1, 0, 0    'appuie sur la touche CTRL
        keybd_event &H41, 1, 0, 0    'appuie sur la touche A
        keybd_event &H41, 0, &H2, 0    'Lacher la touche A
        Temporisation 30
        keybd_event &H43, 1, 0, 0    'appuie sur la touche C
        keybd_event &H43, 0, &H2, 0    'Lacher la touche C
        Temporisation 30
        keybd_event &H11, 0, &H2, 0    'Lacher la touche CTRL
        Temporisation 30
        clip.GetFromClipboard
        T = clip.GetText(1)
        DoEvents
    Loop

    'simulate CTRL+F4 keys to close browser window
    keybd_event &H11, 1, 0, 0    'appuie sur la touche CTRL
    keybd_event &H73, 0, 0, 0    'appuie sur la touche F4
    keybd_event &H73, 0, &H2, 0    'Lacher la touche F4
    keybd_event &H11, 0, &H2, 0    'Lacher la touche CTRL

   
    'return on worksheet
    With ThisWorkbook.Worksheets(1)
        .[A1].Select
        .[A1].ClearContents
        .Paste
        GetPDFTextViaExcel = .[A1].Value
    End With
    Set clip = Nothing
End Function

Sub test2()
    GetPDFTextViaExcel "C:\Users\patricktoulon\Desktop\trier un tableau avec la fonction sort d'excel 2023.pdf"
End Sub
je t'ai mis les commentaire en anglais
t'aime bien les commentaires in english toi 🤣🤣🤣🤣
 

Dudu2

XLDnaute Barbatruc
Oui, bien vu.

De mon coté y a une
1700154529076.gif
dans le potage Excel.
Quand je passe par le Sleep 2000 (quand il fonctionne) et que je modifie le code pour passer par le FindWindow, ça fonctionne, de manière répétée.
Si je ré-initialise le projet, ou ferme/ouvre le classeur ça ne fonctionne plus.
Je vais essayer tes keybd_event.
 

patricktoulon

XLDnaute Barbatruc
Oui, bien vu.

De mon coté y a une Regarde la pièce jointe 1183942 dans le potage Excel.
Quand je passe par le Sleep 2000 (quand il fonctionne) et que je modifie le code pour passer par le FindWindow, ça fonctionne, de manière répétée.
Si je ré-initialise le projet, ou ferme/ouvre le classeur ça ne fonctionne plus.
Je vais essayer tes keybd_event.
donne moi ton code tel quel
 

Dudu2

XLDnaute Barbatruc
C'est infernal. Un coup ça marche. je bouge un truc insignifiant dans le code, ça marche plus.
Tu peux essayer de jouer avec les flags:
Const DOSLEEP = False
Const DOFINDWINDOW = True
J'ai tout essayé.

Code:
Option Explicit

Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassname As String, ByVal lpWindowName As String) As LongPtr
Private Declare PtrSafe Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As LongPtr, ByVal wMsg As Long, ByVal wParam As Long, lParam As Long) As Long
'
Private Const WM_CLOSE As Integer = &H10

'-----------------------------------------
'Open a PDF and copy the text in the sheet
'-----------------------------------------
Function GetPDFTextViaExcel(FichierPDF As String) As String
    Dim ChromeExe As String
    Dim NomPDF As String
    Dim hWnd As LongPtr
    '
    Const Chrome64 = "C:\Program Files\Google\Chrome\Application\chrome.exe"
    Const Chrome32 = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
    
    If Len(Dir(Chrome64)) > 0 Then
        ChromeExe = Chrome64
    ElseIf Len(Dir(Chrome32)) > 0 Then
        ChromeExe = Chrome32
    Else
        MsgBox "Chrome.exe non trouvé !"
        Exit Function
    End If
    
    'PDF file name
    NomPDF = Mid(FichierPDF, InStrRev(FichierPDF, "\") + 1)

    'Kill possible existing Windows
    Do While 1
        hWnd = FindWindow(vbNullString, NomPDF & " - Google Chrome")
        If Not hWnd = 0 Then
            Call SendMessage(hWnd, WM_CLOSE, 0, 0)
            DoEvents
        Else
            Exit Do
        End If
    Loop

    'Run Chrome and wait for the Window to be ready
    Call Shell(ChromeExe & " --new-window -url " & """" & FichierPDF & """", vbNormalFocus)
    
Const DOSLEEP = False
Const DOFINDWINDOW = True
    
If DOFINDWINDOW Then
    Do While hWnd = 0
        hWnd = FindWindow(vbNullString, NomPDF & " - Google Chrome")
        Temporisation 1000
    Loop
End If

If DOSLEEP Then
    Sleep 2000
End If

    'Send keys to Select All / Copy / Kill the application
    Call SendKeysCopyPasteClose
    
    With ThisWorkbook.Worksheets(1)
        .[A1].Select
        .[A1].ClearContents
        On Error Resume Next
        .Paste
        On Error GoTo 0
        GetPDFTextViaExcel = .[A1].Value
    End With
End Function

Private Sub SendKeysCopyPasteClose()
    Const Tempo = 1000
    
    CreateObject("wscript.shell").SendKeys "^a"
    Temporisation Tempo
    CreateObject("wscript.shell").SendKeys "{TAB}"
    Temporisation Tempo
    CreateObject("wscript.shell").SendKeys "^c"
    Temporisation Tempo
    CreateObject("wscript.shell").SendKeys "%{F4}"
End Sub

'-------------
'Temporisation
'-------------
Private Sub Temporisation(NbDoEvents As Integer)
    Dim k As Integer
    
    For k = 1 To NbDoEvents
        DoEvents
    Next k
End Sub
 

patricktoulon

XLDnaute Barbatruc
bon ben c'est bien ce que je pensais
on est bloqué sur le do loop après shell
chez moi sur chrome et firefox le titre de la fenêtre est celui intégré au pdf
j'ai le prefixe "VBA -"+titre du fichier
si tu veux continuer dans ce sens il te faut la findwindowpart
je sais plus avec qui j'ai fait ca
 

Dudu2

XLDnaute Barbatruc
Je pense que le FindWindow n'est pas suffisant pour déterminer si la fenêtre est prête à recevoir les SendKeys.
Le FindWindow peut aider à attendre que Chrome soit lancé, mais il faut un Sleep de précaution après quand même.

En faisant ça, ça a l'air de fonctionner:
Code:
Const DOFINDWINDOW = True
Const DOSLEEP = True
   
If DOFINDWINDOW Then
    Do While hWnd = 0
        hWnd = FindWindow(vbNullString, NomPDF & " - Google Chrome")
        Temporisation 1000
    Loop
End If

If DOSLEEP Then
    Sleep 500
End If
 

patricktoulon

XLDnaute Barbatruc
re
oui mais ca ne fonctionnera pas tout le temps
regarde le text des fenêtre ouverte qu'il me trouve a chaque lancement
et sur chrome c'est deux fois plus lent
comme tu peux le voir le titre change
on a eu la même idée moi j'ai mis un sleep 1000
et pourtant j'utilise la findwindowbyparttitle pour être su de tomber dessus
1700160737867.png


non c'est vraiment trop bancale @Dudu2 ca a fonctionner une fois su une bonne 30aines de fois

profite en quand même pour récupérer la FindWindoWByPartTitle
VB:
Option Explicit

Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassname As String, ByVal lpWindowName As String) As LongPtr
Private Declare PtrSafe Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As LongPtr, ByVal wMsg As Long, ByVal wParam As Long, lParam As Long) As Long
Private Declare PtrSafe Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hWnd As LongPtr, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare PtrSafe Function GetWindow Lib "user32" (ByVal hWnd As LongPtr, ByVal wCmd As Long) As Long
'
Private Const WM_CLOSE As Integer = &H10

Function FindWindoWByPartTitle(Optional partTittle As String)
    Dim sStr As String, hWnd As LongPtr
    sStr = Space$(150)
   hWnd = FindWindow(vbNullString, vbNullString)
      Do While hWnd <> 0
        GetWindowText hWnd, sStr, 300
           If "x" & sStr & "x" Like "*" & partTittle & "*" Then
            Debug.Print Trim(sStr)
            FindWindoWByPartTitle = hWnd
            Exit Function
        End If
        hWnd = GetWindow(hWnd, 2)
    Loop
End Function

Sub test()
GetPDFTextViaExcel "C:\Users\patricktoulon\Desktop\trier un tableau avec la fonction sort d'excel 2023.pdf"
End Sub
'-----------------------------------------
'Open a PDF and copy the text in the sheet
'-----------------------------------------
Function GetPDFTextViaExcel(FichierPDF As String) As String
    Dim ChromeExe As String
    Dim NomPDF As String
    Dim hWnd As LongPtr
    '
    'Const Chrome64 = "C:\Program Files\Google\Chrome\Application\chrome.exe"
    'Const Chrome32 = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
    
    Const Chrome64 = "C:\Program Files\Mozilla Firefox\firefox.exe"
    Const Chrome32 = "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
  
    If Len(Dir(Chrome64)) > 0 Then
        ChromeExe = Chrome64
    ElseIf Len(Dir(Chrome32)) > 0 Then
        ChromeExe = Chrome32
    Else
        MsgBox "Chrome.exe non trouvé !"
        Exit Function
    End If
    
    'PDF file name
    NomPDF = Mid(FichierPDF, InStrRev(FichierPDF, "\") + 1)

    'Kill possible existing Windows
    Do While 1
        hWnd = FindWindoWByPartTitle(NomPDF)
        If Not hWnd = 0 Then
            Call SendMessage(hWnd, WM_CLOSE, 0, 0)
            DoEvents
        Else
            Exit Do
        End If
    Loop

    'Run Chrome and wait for the Window to be ready
    Call Shell(ChromeExe & " --new-window -url " & """" & FichierPDF & """", vbNormalFocus)
    Sleep 1000
Const DOSLEEP = False
Const DOFINDWINDOW = True
    
If DOFINDWINDOW Then
    Do While hWnd = 0
        hWnd = FindWindoWByPartTitle(NomPDF)
        Sleep 1000
    Loop
End If
Sleep 500
    'Send keys to Select All / Copy / Kill the application
     SendKeysCopyPasteClose
     With ThisWorkbook.Worksheets(1)
        .[A1].Select
        .[A1].ClearContents
        On Error Resume Next
        .Paste
        On Error GoTo 0
        GetPDFTextViaExcel = .[A1].Value
    End With
End Function

Private Sub SendKeysCopyPasteClose()
    Const Tempo = 50
    
    CreateObject("wscript.shell").SendKeys "^a"
    Temporisation Tempo
    CreateObject("wscript.shell").SendKeys "{TAB}"
    Temporisation Tempo
    CreateObject("wscript.shell").SendKeys "^c"
    Temporisation Tempo
    CreateObject("wscript.shell").SendKeys "%{F4}"
End Sub

'-------------
'Temporisation
'-------------
Private Sub Temporisation(NbDoEvents As Integer)
    Dim k As Integer
    
    For k = 1 To NbDoEvents
        DoEvents
    Next k
End Sub
 

Dudu2

XLDnaute Barbatruc
Je sais plus trop ce qui fonctionne ou pas :cool:. Pour l'instant ça roule chez moi. Faut que je valide chez la personne qui en a besoin.

En fait au début je ne cherche pas TOUTES les fenêtres de Chrome, seulement celles relatives au fichier PDF. C'était pour épurer les fenêtres résiduelles non fermées issues de mes plantages. Et ultérieurement pour être sûr dans la boucle d'attente de Chrome de ne pas retomber sur une de ces vieilles fenêtres résiduelles.

La fonction que tu as appelée FindWindoWByPartTitle j'en ai une équivalente qui part de la DesktopWindow et que j'ai appelée GetWindowByPartialName. Mais merci quand même.
 

Dudu2

XLDnaute Barbatruc
Je met ici la solution que j'utilise qui remplace la solution initialement fournie.
Edit: Voir aussi la solution de @patricktoulon ci-dessous.
VB:
Option Explicit
'
Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassname As String, ByVal lpWindowName As String) As LongPtr
Private Declare PtrSafe Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As LongPtr, ByVal wMsg As Long, ByVal wParam As Long, lParam As Long) As Long
Private Declare PtrSafe Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
'
Private Const WM_CLOSE As Integer = &H10

'-----------------------
'Returns a PDF file text
'-----------------------
Function GetPDFText(FichierPDF As String) As String
    Dim Clipboard As New MSForms.DataObject 'Reference Microsoft Forms 2.0 Object Library (or add and delete a USerForm)
    Dim ChromeExe As String
    Dim NomPDF As String
    Dim hWnd As LongPtr
    '
    Const Chrome64 = "C:\Program Files\Google\Chrome\Application\chrome.exe"
    Const Chrome32 = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
    Const SleepTime = 500
  
    'Check file
    If Len(Dir(FichierPDF)) = 0 Then
        MsgBox "Fichier <" & FichierPDF & "> non trouvé !"
        Exit Function
    End If
  
    'Check Chrome
    If Len(Dir(Chrome64)) > 0 Then
        ChromeExe = Chrome64
    ElseIf Len(Dir(Chrome32)) > 0 Then
        ChromeExe = Chrome32
    Else
        MsgBox "Chrome.exe non trouvé !"
        Exit Function
    End If
  
    'PDF file name
    NomPDF = Mid(FichierPDF, InStrRev(FichierPDF, "\") + 1)
  
    'Empty the Clipboard
    With Clipboard
        .SetText ""
        .PutInClipboard
    End With

    'Kill possible existing Windows
    Do While 1
        hWnd = FindWindow(vbNullString, NomPDF & " - Google Chrome")
        If Not hWnd = 0 Then
            Call SendMessage(hWnd, WM_CLOSE, 0, 0)
            DoEvents
        Else
            Exit Do
        End If
    Loop

    'Run Chrome and wait for the Window to be ready
    Call Shell(ChromeExe & " --new-window -url " & """" & FichierPDF & """", vbNormalFocus)
  
    Do While hWnd = 0
        hWnd = FindWindow(vbNullString, NomPDF & " - Google Chrome")
        Temporisation 1000
    Loop
  
    Sleep SleepTime

    'Send keys to Select All / Copy / Kill the application
    Call SendKeysSelectCopyClose
  
    'Get Clipboard data
    With Clipboard
        .GetFromClipboard
        On Error Resume Next
        GetPDFText = .GetText
        On Error GoTo 0
    End With
End Function

'----------------------------
'Envoi des touches sur Chrome
'----------------------------
Private Sub SendKeysSelectCopyClose()
    Const Tempo = 1000

    SendKeybd "A", "ctrl"   'Touche Ctrl A
    Temporisation Tempo
  
    SendKeybd &H9           'Touche TAB
    Temporisation Tempo

    SendKeybd "C", "ctrl"   'Touche CTRL C
    Temporisation Tempo
  
    SendKeybd &H73, "alt"   'Touche ALT F4
End Sub

'--------------------------------------------
'Wrap keybd_event
'Alter = "down", "up", "shift", "ctrl", "alt"
'E.g. SendKeybd &H43, "ctrl" 'Send Ctrl C
'https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
'--------------------------------------------
Sub SendKeybd(ByVal Key As Variant, Optional ByVal Alter As String = "")
    Dim AlterValue As Byte
  
    If VarType(Key) = vbString Then Key = Asc(Key)
  
    Select Case UCase(Alter)
        Case "DOWN"
            keybd_event Key, 1, 0, 0
        Case "UP"
            keybd_event Key, 0, 2, 0
        Case "SHIFT"
            AlterValue = &H10
            GoSub AlterKey
        Case "CTRL"
            AlterValue = &H11
            GoSub AlterKey
        Case "ALT"
            AlterValue = &H12
            GoSub AlterKey
        Case Else
            GoSub DownUp
    End Select
    Exit Sub
  
AlterKey:
    keybd_event AlterValue, 1, 0, 0
    GoSub DownUp
    keybd_event AlterValue, 0, 2, 0
    Return
  
DownUp:
    keybd_event Key, 1, 0, 0
    keybd_event Key, 0, 2, 0
    Return
End Sub

'-------------
'Temporisation
'-------------
Private Sub Temporisation(NbDoEvents As Integer)
    Dim k As Integer
  
    For k = 1 To NbDoEvents
        DoEvents
    Next k
End Sub
 
Dernière édition:

patricktoulon

XLDnaute Barbatruc
ben perso je préfère ma version
je n'est pas de raté
je n'ai pas de problème de pavé déactivé sur les versions 32 bits
je ne met pas plus de temps que necessaire puisque c'est le clip qui oui ou non
un seul sleep 1000 ou 1500 sur mon portable apres la temporisation c'est 10 millièmes et pas plus
VB:
'******************************************************************************************************************************************************
'    ___     _     _______  __      _  ____  _   _  _______  ___      _   _  _    ___      _     _.
'   //  \\  /\\      //    // \\   // //    //  //    //    //  \\   //  // //   //  \\   //|   //
'  //___// //__\    //    //__//  // //    //__||    //    //   //  //  // //   //   //  // |  //
' //      //   \\  //    //  \\  // //    //  \\    //    //   //  //  // //   //   //  //  | //
'//      //    // //    //   // // //___ //    \\  //     \\__//  //__// //___ \\__//  //   |//
'******************************************************************************************************************************************************
'-----------------------------------------
'pdf grabber
'[@patricktoulon] on exceldownloads
'adding Chrome firefox control in an select case
'reduction of (window ready wait times) for  (chrome or firefox)
'new process
'we no longer manage the window with the APIs
'we are working on clipboard wait management
'non-empty clipboard wait loop
'loading time lasts the time the clipboard takes to load the data
'updated V 2
'replacing wscript.shell.sendkeys
'by simulating keys with Api keybd_event
'the numeric keypad is no longer disabled
'-----------------------------------------
Option Explicit
Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Declare PtrSafe Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)

Sub Temporisation(NbDoEvents As Integer)
  '@dudu2 sur exceldownloads
  Dim k As Integer
     For k = 1 To NbDoEvents
        DoEvents
    Next k
End Sub
Function GrabbTextInPdF(FichierPDF As String) As String
    Dim nav$, T$, clip As Object, wshshell As Object

    Cells(1, 1).CurrentRegion.ClearContents
    'browser path constantes
    Const nav1 = "C:\Program Files\Google\Chrome\Application\chrome.exe"
    Const nav2 = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
    Const nav3 = "C:\Program Files\Mozilla Firefox\firefox.exe"
    Const nav4 = "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"

    'select case true to find the browser installed on your system
    Select Case True
    Case Dir(nav1) <> "": nav = nav1
    Case Dir(nav2) <> "": nav = nav2
    Case Dir(nav4) <> "": nav = nav4
    Case Dir(nav3) <> "": nav = nav3    'je met le nav3 en premier je préfère firefox64
    Case Else
    End Select

    'we create the clipboard object (late binding)no reference required
    ' we empty the clipboard
    Set clip = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
    clip.SetText "": clip.PutInClipboard

    'run the browser chosen in the select case
    Call Shell(nav & " --new-window -url " & """" & FichierPDF & """", vbNormalFocus)

    'we still leave a minimum of 1 second for the window to be ready
    'even if the document is not completely loaded
    Sleep 1000 'increase if necessary

    'creating the wscript.shell object(no reference required)
    'Set wshshell = CreateObject("wscript.shell")


    'loop and  simulating (CTRL+A and C keys) as long as the clipboard is not full
    Do While Len(T) = 0
        keybd_event &H11, 1, 0, 0    'appuie sur la touche CTRL
        keybd_event &H41, 1, 0, 0    'appuie sur la touche A
        keybd_event &H41, 0, &H2, 0    'Lacher la touche A
        Temporisation 10
        keybd_event &H43, 1, 0, 0    'appuie sur la touche C
        keybd_event &H43, 0, &H2, 0    'Lacher la touche C
        Temporisation 10
        keybd_event &H11, 0, &H2, 0    'Lacher la touche CTRL
        Temporisation 30
        clip.GetFromClipboard
        T = clip.GetText(1)
        DoEvents
    Loop

    'simulate CTRL+F4 keys to close browser window
    keybd_event &H11, 1, 0, 0    'appuie sur la touche CTRL
    keybd_event &H73, 0, 0, 0    'appuie sur la touche F4
    keybd_event &H73, 0, &H2, 0    'Lacher la touche F4
    keybd_event &H11, 0, &H2, 0    'Lacher la touche CTRL

    Temporisation 10
       
    'return on worksheet
    With ThisWorkbook.Worksheets(1)
        .[A1].Select
        .[A1].ClearContents
        .Paste
        GrabbTextInPdF = .[A1].Value
    End With
    Set clip = Nothing
End Function

Sub test2()
    GrabbTextInPdF "C:\Users\patricktoulon\Desktop\trier un tableau avec la fonction sort d'excel 2023.pdf"
End Sub
 

Dudu2

XLDnaute Barbatruc
Bonjour,
Si tu dis qu'en 32 bits le CreateObject("wscript.shell").SendKeys désactive le pavé numérique, c'est nouveau pour moi car je pensais cette méthode infaillible.
Donc j'ai aussi adopté le keybd_event pour envoyer les touches en utilisant une fonction qu'il faudrait idéalement revoir pour lui envoyer les mêmes arguments que pour un SendKeys.
 
Dernière édition:

patricktoulon

XLDnaute Barbatruc
re
Si tu dis qu'en 32 bits le CreateObject("wscript.shell").SendKeys désactive le pavé numérique, c'est nouveau pour moi car je pensais cette méthode infaillible.
je te le confirme que l'utilisation de wscript.shell pour les sendkeys n'est plus un gage de certitude quand a la déactivation du pavé et cela depuis longtemps même
j'etais encore sur 2007 qu'il y avait des déactivations déjà
le seul intérêt à l'utiliser c'est pour taper sur des applications externes à excel
bien faire la différence entre
sendkeys
wscript.sell.sendkeys
application.sendkeys
les 3 ont des fonctionnement et contraintes différentes
 

Discussions similaires

Statistiques des forums

Discussions
312 664
Messages
2 090 676
Membres
104 633
dernier inscrit
benabidwajih