+ Reply to Thread
Results 1 to 28 of 28

Close Acrobat from VBA if it tries to open a corrupt file

Hybrid View

  1. #1
    Registered User
    Join Date
    04-28-2013
    Location
    Stockholm
    MS-Off Ver
    Excel 2007
    Posts
    93

    Close Acrobat from VBA if it tries to open a corrupt file

    Hello everyone,

    I have used some VBA code to download numerous files from the web. I saved them all with the .pdf extension, even if some of them are not pdf files.

    Then, in another piece of code I open the documents one by one and check if I can find a given word.

    A problem appears when Acrobat tries to open a file which is not a pdf file. A window from Acrobat pops up with the usual error "....not a supported file format...." but I'm struglling to close the Acrobat app from VBA. I tried "App.Exit", "AVDoc.Close True" without any notable success.

    All suggestions are appreciated!

  2. #2
    Registered User
    Join Date
    04-28-2013
    Location
    Stockholm
    MS-Off Ver
    Excel 2007
    Posts
    93

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    This is the actual code that I am using, borrowed from Christos Samaras. Even though the author tries to account for potential problems, mine is a bit more specific that does not follow into any of these categories. In other words, I am able to start Acrobat, Acrobat tries to open the file, file is not a genuine PDF file. Then a message box appears from Acrobat itself, warning me that the file is not supportef format or corrupted etc. The issue is that I have to manually click on the OK button of this Acrobat message box so that the programme can be closed, error message "Could not open the PDF file" appears in my Excel document and the code resumes with the next iteration, which is not feasible for me. Ideal solution would be to find a way to close Acrobat automatically from VBA after this message box appears.



    Sub FindTextInPDF()
          
        '----------------------------------------------------------------------------------------
        'This macro can be used to find a specific TEXT (more than one word) in a PDF document.
        'The macro opens the PDF, finds the specified text (the first instance), scrolls so
        'that it is visible and highlights it.
        'The macro uses the FindText method (see the code below for more info).
        
        'Note that in some cases it doesn't work (doesn't highlight the text), so in those
        'cases prefer the SearchTextInPDF macro, if you have only ONE WORD to find!
    
        'The code uses late binding, so no reference to external library is required.
        'However, the code works ONLY with Adobe Professional, so don't try to use it with
        'Adobe Reader because you will get an "ActiveX component can't create object" error.
        
        'Written by:    Christos Samaras
        'Date:          04/05/2014
        'e-mail:        [email protected]
        'site:          http://www.myengineeringworld.net
        '----------------------------------------------------------------------------------------
    
        'Declaring the necessary variables.
        Dim TextToFind  As String
        Dim PDFPath     As String
        Dim App         As Object
        Dim AVDoc       As Object
        Dim SpecFl      As String
        Dim i           As Integer
        Dim acrobatID
        Dim acrobatInvokeCmd As String
        Dim acrobatLocation As String
        
        
        acrobatLocation = "C:\Program Files (x86)\Adobe\Acrobat DC\Acrobat\Acrobat.exe"
        
        acrobatInvokeCmd = acrobatLocation & " " & PDFPath
        
        For i = 2 To 5000
                   
            'Specify the text you want to search.
            'TextToFind = "Christos Samaras"
            'Using a range:
            TextToFind = ThisWorkbook.Sheets("Sheet1").Cells(i, 2).Value
                   
            SpecFl = ThisWorkbook.Sheets("Sheet1").Cells(i, 1).Value & ".pdf"
                   
            'Specify the path of the sample PDF form.
            'Full path example:
            'PDFPath = "C:\Users\Christos\Desktop\How Software Companies Die.pdf"
            'Using workbook path:
            'PDFPath = ThisWorkbook.Path & "\" & "How Software Companies Die.pdf"
            'Using a range:
            PDFPath = ThisWorkbook.Path & "\" & SpecFl
           
            'Check if the file exists.
            If Dir(PDFPath) = "" Then
                Cells(i, 3).Value = "Cannot find the PDF file!"
                Exit Sub
            End If
           
            'Check if the input file is a PDF file.
            If LCase(Right(PDFPath, 3)) <> "pdf" Then
                Cells(i, 3).Value = "The input file is not a PDF file!"
                'Close the Acrobat application.
              
                Exit Sub
            End If
            
            On Error Resume Next
            
            'Initialize Acrobat by creating the App object.
            Set App = CreateObject("AcroExch.App")
            
            'Check if the object was created. In case of error release the object and exit.
            If Err.Number <> 0 Then
                MsgBox "Could not create the Adobe Application object!", vbCritical, "Object Error"
                Set App = Nothing
                Exit Sub
            End If
            
            'Create the AVDoc object.
            Set AVDoc = CreateObject("AcroExch.AVDoc")
            
            'Check if the object was created. In case of error release the objects and exit.
            If Err.Number <> 0 Then
                MsgBox "Could not create the AVDoc object!", vbCritical, "Object Error"
                Set AVDoc = Nothing
                Set App = Nothing
                Exit Sub
            End If
            
            On Error GoTo 0
            
            'Open the PDF file.
            If AVDoc.Open(PDFPath, "") = True Then
                
                'Open successful, bring the PDF document to the front.
                AVDoc.BringToFront
                
                'Use the FindText method in order to find and highlight the desired text.
                'The FindText method returns true if the text was found or false if it was not.
                'Here are the 4 arguments of the FindText methd:
                'Text to find:          The text that is to be found (in this example the TextToFind variable).
                'Case sensitive:        If true, the search is case-sensitive. If false, it is case-insensitive (in this example is True).
                'Whole words only:      If true, the search matches only whole words. If false, it matches partial words (in this example is True).
                'Search from 1st page:  If true, the search begins on the first page of the document. If false, it begins on the current page (in this example is False).
                If AVDoc.FindText(TextToFind, False, True, True) = True Then
        
                    'Text was not found, close the PDF file without saving the changes.
                    AVDoc.Close True
                    
                    'Close the Acrobat application.
                    App.Exit
                       
                    'Release the objects.
                    Set AVDoc = Nothing
                    Set App = Nothing
                    
                    'Inform the user.
                    Cells(i, 3).Value = "Text is found in the PDF file"
                    
                Else
                
                     'Text was not found, close the PDF file without saving the changes.
                    AVDoc.Close True
                    
                    'Close the Acrobat application.
                    App.Exit
                       
                    'Release the objects.
                    Set AVDoc = Nothing
                    Set App = Nothing
                    
                    'Inform the user.
                    Cells(i, 3).Value = "Text not found in the PDF file"
                
                End If
                
            Else
            
                
    
                
                'Text was not found, close the PDF file without saving the changes.
                AVDoc.Close True
                
                'Unable to open the PDF file, close the Acrobat application.
                App.Exit
        
                'Release the objects.
                'Set AVDoc = Nothing
                'Set App = Nothing
                
               
                
                'Inform the user.
                Cells(i, 3).Value = "Could not open the PDF file!"
                
                
                End If
        
        Next i
        
    End Sub

  3. #3
    Valued Forum Contributor fredlo2010's Avatar
    Join Date
    07-04-2012
    Location
    Miami, United States
    MS-Off Ver
    Excel 365
    Posts
    762

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    Hi,

    See if this code helps.

    The code needs reference to the Acrobat library. If you do not know how to add a reference you can find an easy tutorial here. https://msdn.microsoft.com/en-us/lib...=vs.85%29.aspx


    Hope this helps.

    
    
    
    Sub FindTextInPDF()
    
        Dim oAcroApp As Acrobat.AcroApp
        Dim oAcroDoc As Acrobat.AcroAVDoc
        Dim shData As Worksheet
        Dim strTextToFind As String
        Dim strPDFPath As String
        Dim lRow As Long
        Dim i As Long
    
        ' Create the acrobat objects
        On Error GoTo Error_Handler
    
        Set oAcroApp = New Acrobat.AcroApp
        Set oAcroDoc = New Acrobat.AcroAVDoc
        Set shData = ThisWorkbook.Sheets("Sheet1")
        lRow = shData.Cells(shData.Rows.Count, 1).End(xlUp).Row
        
    
        ' Loop through the data
        For i = 2 To lRow
            
            ' Get path and string to find
            strTextToFind = shData.Cells(i, 2).Value
            strPDFPath = ThisWorkbook.Path & "\" & shData.Cells(i, 1).Value & ".pdf"
    
            ' Check if the file exists
            If DoesFileExist(strPDFPath) Then
                If Not oAcroDoc Is Nothing Then
                    If oAcroDoc.Open(strPDFPath, strPDFPath) Then
    
                        'Open successful, bring the PDF document to the front.
                        oAcroDoc.BringToFront
    
                        If oAcroDoc.FindText(strTextToFind, False, True, True) Then
                            shData.Cells(i, 3).Value = "Text is found in the PDF file"
                        Else
                            shData Cells(i, 3).Value = "Text not found in the PDF file"
                        End If
                        
                        ' Close the document
                        oAcroDoc.Close False
                    Else
                        MsgBox "Cannot open the PDF file!"
                    End If
                Else
                    MsgBox "Cannot create instance of Object!"
                End If
            Else
                MsgBox "Cannot find the PDF file!"
            End If
        Next
        
    Exit_Handler:
    
        On Error GoTo 0
        
        ' Clean up
        oAcroApp.Exit
        Set oAcroDoc = Nothing
        Set oAcroApp = Nothing
        
        Exit Sub
    
    Error_Handler:
    
        MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure FindTextInPDF"
    
        Resume Exit_Handler
    
    End Sub
    
    ' Function to check if the file exists
    Function DoesFileExist(ByVal strPath As String) As String
        DoesFileExist = (Not Dir(strPath) = vbNullString)
    End Function
    
    ' Turn extra features off for faster code
    Sub TurnExtrasOff()
        With Application
            .ScreenUpdating = False
            .EnableEvents = False
            .Calculation = xlCalculationManual
        End With
    End Sub
        
    ' Turn the extra features back on
    Sub TurnExtrasOn()
        With Application
            .ScreenUpdating = True
            .EnableEvents = True
            .Calculation = xlCalculationAutomatic
        End With
    End Sub
    Thanks

  4. #4
    Registered User
    Join Date
    04-28-2013
    Location
    Stockholm
    MS-Off Ver
    Excel 2007
    Posts
    93

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    Hi,

    Thanks for helpful reply!

    I tried your code, adding the reference before running.

    It opens the first pdf file and then a dialog box appears saying: "Error 438 (Object doesn't support this property or method) in procedure.....

    Do you think I missed some reference or is it something else?

  5. #5
    Registered User
    Join Date
    04-28-2013
    Location
    Stockholm
    MS-Off Ver
    Excel 2007
    Posts
    93

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    I tried it on a new document and it says "Error in loading DLL" so I guess it must be something with the references.

  6. #6
    Valued Forum Contributor fredlo2010's Avatar
    Join Date
    07-04-2012
    Location
    Miami, United States
    MS-Off Ver
    Excel 365
    Posts
    762

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    Hi,

    Make sure you are adding this one

    Capture.PNG


    Thanks

  7. #7
    Registered User
    Join Date
    04-28-2013
    Location
    Stockholm
    MS-Off Ver
    Excel 2007
    Posts
    93

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    Hi again,

    I`m adding exactly this one, learned my lesson from a previous issue with Excel, but it doesn`t change anything. First pdf file is opened and Excel freezes with the error message box.

  8. #8
    Valued Forum Contributor fredlo2010's Avatar
    Join Date
    07-04-2012
    Location
    Miami, United States
    MS-Off Ver
    Excel 365
    Posts
    762

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    It's working for me.

    I wonder if there is a scrip on the pdf maybe causing trouble.

    Can you step through the code with F8? How far can you go ?

    Thanks

  9. #9
    Registered User
    Join Date
    04-28-2013
    Location
    Stockholm
    MS-Off Ver
    Excel 2007
    Posts
    93

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    I think it goes to


      Else
                            shData Cells(i, 3).Value = "Text not found in the PDF file"
    and then jumps to the Error handler and shows the message box. There is nothing filled in the worksheet related to the outcome from the iteration (text found, not found, etc.)

  10. #10
    Valued Forum Contributor fredlo2010's Avatar
    Join Date
    07-04-2012
    Location
    Miami, United States
    MS-Off Ver
    Excel 365
    Posts
    762

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    I am sorry I apologize it was my mistake I am missing a dot between the sheet name and cell

    The line in the else should be :

    shData.Cells(i, 3).Value = "Text not found in the PDF file"
    Thanks

  11. #11
    Forum Guru Kyle123's Avatar
    Join Date
    03-10-2010
    Location
    Leeds
    MS-Off Ver
    365 Win 11
    Posts
    7,238

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    Why not just not save files that aren't PDFs as PDFs, this kind of feels like closing the stable door after the horse has bolted

  12. #12
    Registered User
    Join Date
    04-28-2013
    Location
    Stockholm
    MS-Off Ver
    Excel 2007
    Posts
    93

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    It is my mistake not spotting the missing dot. Thanks, the code works now, but the problem still persists - after the dialog box from Acrobat appears when it tries to open the non-PDF file saved as PDF, Acrobat has to be closed manually.

    Kyle123, another piece of code is used to download files from a list of URLs. I'm not sure it would be possible to apply your suggestion there.

  13. #13
    Forum Guru Kyle123's Avatar
    Join Date
    03-10-2010
    Location
    Leeds
    MS-Off Ver
    365 Win 11
    Posts
    7,238

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    So change the other bit of code? - this is just treating the symptoms and not addressing the cause

  14. #14
    Valued Forum Contributor fredlo2010's Avatar
    Join Date
    07-04-2012
    Location
    Miami, United States
    MS-Off Ver
    Excel 365
    Posts
    762

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    Hi again,

    I am sorry for all the mishaps. This code will help you with what you need a think.

    Sub FindTextInPDF()
    
        Dim oAcroApp As Acrobat.AcroApp
        Dim oAcroDoc As Acrobat.AcroAVDoc
        Dim shData As Worksheet
        Dim strTextToFind As String
        Dim strPDFPath As String
        Dim lRow As Long
        Dim i As Long
    
        ' Create the acrobat objects
        On Error GoTo Error_Handler
    
        Set oAcroApp = New Acrobat.AcroApp
        Set oAcroDoc = New Acrobat.AcroAVDoc
        Set shData = ThisWorkbook.Sheets("Sheet1")
        lRow = shData.Cells(shData.Rows.Count, 1).End(xlUp).Row
        
        ' Loop through the data
        For i = 2 To lRow
            
            ' Get path and string to find
            strTextToFind = shData.Cells(i, 2).Value
            strPDFPath = ThisWorkbook.Path & "\" & shData.Cells(i, 1).Value
            strPDFPath = GetFileName(strPDFPath)
            
            
            ' Check if the file exists
            If Not strPDFPath = vbNullString Then
                
                'Create the full name
                strPDFPath = ThisWorkbook.Path & "\" & strPDFPath
                
                If Not oAcroDoc Is Nothing Then
                    If oAcroDoc.Open(strPDFPath, strPDFPath) Then
    
                        'Open successful, bring the PDF document to the front.
                        oAcroDoc.BringToFront
    
                        If oAcroDoc.FindText(strTextToFind, False, True, True) Then
                            shData.Cells(i, 3).Value = "Text is found in the PDF file"
                        Else
                            shData.Cells(i, 3).Value = "Text not found in the PDF file"
                        End If
                        
                        ' Close the document
                        oAcroDoc.Close False
                    Else
                        MsgBox "Cannot open the PDF file!"
                    End If
                Else
                    MsgBox "Cannot create instance of Object!"
                End If
            Else
                MsgBox "Cannot find the PDF file!"
            End If
        Next
        
    Exit_Handler:
    
        On Error GoTo 0
        
        ' Clean up
        oAcroApp.Exit
        Set oAcroDoc = Nothing
        Set oAcroApp = Nothing
        
        Exit Sub
    
    Error_Handler:
    
        MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure FindTextInPDF"
    
        Resume Exit_Handler
    
    End Sub
    
    ' Function to check if the file exists
    Function GetFileName(ByVal strPath As String) As String
        GetFileName = Dir(strPath & "*.pdf", vbNormal)
    End Function
    
    ' Turn extra features off for faster code
    Sub TurnExtrasOff()
        With Application
            .ScreenUpdating = False
            .EnableEvents = False
            .Calculation = xlCalculationManual
        End With
    End Sub
        
    ' Turn the extra features back on
    Sub TurnExtrasOn()
        With Application
            .ScreenUpdating = True
            .EnableEvents = True
            .Calculation = xlCalculationAutomatic
        End With
    End Sub
    Thanks

    Sorry again lol

  15. #15
    Registered User
    Join Date
    04-28-2013
    Location
    Stockholm
    MS-Off Ver
    Excel 2007
    Posts
    93

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    fredlo2010,

    Can't express my gratitude for your help and suggestion! I don't think this issue can be solved though. Tried a lot of things (different ways of closing the programme, SendKeys), asked around, searched for it and there doesn't seem to be any solution. Perhaps dialog boxes coming from Acrobat are outside the reach of VBA.

    I'll check to see if I can twist my other code that downloads the file.

  16. #16
    Forum Guru Kyle123's Avatar
    Join Date
    03-10-2010
    Location
    Leeds
    MS-Off Ver
    365 Win 11
    Posts
    7,238

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    An example of downloading a document only if it's a pdf. It will take the document title if it has one, if not you can specify a file name.

    This will save the file to the desktop and will overwrite any document with the same name:
    Sub test()
    
        Const DefaultFileName = "MyFile.pdf"
        
        Dim fileType As String
        Dim filename As String
        Dim temp As String
    
        With CreateObject("winhttp.winhttprequest.5.1")
    
            .Open "GET", "https://takeielts.britishcouncil.org/sites/default/files/Listening_practice_questions_121012.pdf", False
            .send
            
            'Get the MIME filetype
            extension = .getresponseheader("Content-Type")
            
            'If there's a Content-Disposition Header, it will have the default filename
            On Error Resume Next
                filename = Split(.getresponseheader("Content-Disposition"), "filename=")(1)
            On Error GoTo 0
            
            'If there's no Disposition Header use the default filename
            If Len(filename) = 0 Then filename = DefaultFileName
            
            'Does the file-type contain "pdf" - if so save it
            If InStr(1, LCase(extension), "pdf") Then
                Dim stream As Object: Set stream = CreateObject("ADODB.Stream")
                stream.Type = 1
                stream.Open
                stream.write .responsebody
                stream.SaveToFile CreateObject("WScript.Shell").specialfolders("Desktop") & "\" & filename, 2
            End If
        End With
    
    End Sub

  17. #17
    Valued Forum Contributor fredlo2010's Avatar
    Join Date
    07-04-2012
    Location
    Miami, United States
    MS-Off Ver
    Excel 365
    Posts
    762

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    Did you try my new code ?

    Can you provide a sample of the workbook set up ?

    Thanks

  18. #18
    Registered User
    Join Date
    04-28-2013
    Location
    Stockholm
    MS-Off Ver
    Excel 2007
    Posts
    93

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    Kyle123, thanks for your suggestion. I would definitely think about this, however, my code for downloading files is working pretty well and smooth, whereas this one for the text search is just one step away from being completed (a step that turns out to be not that trivial at all). It's not that easy to twist it so that it first asserts that thefile is a genuine PDF file and then downloads it.

    Fredlo, please see the files attached. PDF Search Through VBA.xlsmcorrupted.pdf

    My Excel file and an example of corrupted file that cannot be read by Acrobat. Put some other random PDF files around it, run the code and you'll see what I mean.

    Once again, thank you very much for your time and effort!

  19. #19
    Forum Guru Kyle123's Avatar
    Join Date
    03-10-2010
    Location
    Leeds
    MS-Off Ver
    365 Win 11
    Posts
    7,238
    Why not? If you post your code perhaps we can make some suggestions

  20. #20
    Registered User
    Join Date
    04-28-2013
    Location
    Stockholm
    MS-Off Ver
    Excel 2007
    Posts
    93

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    Here it is again.



    Sub FindTextInPDF()
          
        '----------------------------------------------------------------------------------------
        'This macro can be used to find a specific TEXT (more than one word) in a PDF document.
        'The macro opens the PDF, finds the specified text (the first instance), scrolls so
        'that it is visible and highlights it.
        'The macro uses the FindText method (see the code below for more info).
        
        'Note that in some cases it doesn't work (doesn't highlight the text), so in those
        'cases prefer the SearchTextInPDF macro, if you have only ONE WORD to find!
    
        'The code uses late binding, so no reference to external library is required.
        'However, the code works ONLY with Adobe Professional, so don't try to use it with
        'Adobe Reader because you will get an "ActiveX component can't create object" error.
        
        'Written by:    Christos Samaras
        'Date:          04/05/2014
        'e-mail:        [email protected]
        'site:          http://www.myengineeringworld.net
        '----------------------------------------------------------------------------------------
    
        'Declaring the necessary variables.
        Dim TextToFind  As String
        Dim PDFPath     As String
        Dim App         As Object
        Dim AVDoc       As Object
        Dim SpecFl      As String
        Dim i           As Integer
        Dim acrobatID
        Dim acrobatInvokeCmd As String
        Dim acrobatLocation As String
        Dim workaroundloop As Integer
        Dim lRow As Long
        Dim shData As Worksheet
        
        Set shData = ThisWorkbook.Sheets("Sheet1")
        
        lRow = shData.Cells(shData.Rows.Count, 1).End(xlUp).Row
        
        
        acrobatLocation = "C:\Program Files (x86)\Adobe\Acrobat DC\Acrobat\Acrobat.exe"
        
        acrobatInvokeCmd = acrobatLocation & " " & PDFPath
        
        For i = 2 To lRow
                   
            'Specify the text you want to search.
            'TextToFind = "Christos Samaras"
            'Using a range:
            TextToFind = ThisWorkbook.Sheets("Sheet1").Cells(i, 2).Value
                   
            SpecFl = ThisWorkbook.Sheets("Sheet1").Cells(i, 1).Value & ".pdf"
                   
            'Specify the path of the sample PDF form.
            'Full path example:
            'PDFPath = "C:\Users\Christos\Desktop\How Software Companies Die.pdf"
            'Using workbook path:
            'PDFPath = ThisWorkbook.Path & "\" & "How Software Companies Die.pdf"
            'Using a range:
            PDFPath = ThisWorkbook.Path & "\" & SpecFl
           
           For workaroundloop = 1 To 1
           
                 'Check if the file exists.
                 If Dir(PDFPath) = "" Then
                     Cells(i, 3).Value = "Cannot find the PDF file!"
                     Exit For
                 End If
                
                 'Check if the input file is a PDF file.
                 If LCase(Right(PDFPath, 3)) <> "pdf" Then
                     Cells(i, 3).Value = "The input file is not a PDF file!"
                     'Close the Acrobat application.
                   
                     'Exit Sub
                     Exit For
                 End If
            
            Next
            
            On Error Resume Next
            
            'Initialize Acrobat by creating the App object.
            Set App = CreateObject("AcroExch.App")
            
            'Check if the object was created. In case of error release the object and exit.
            If Err.Number <> 0 Then
                MsgBox "Could not create the Adobe Application object!", vbCritical, "Object Error"
                Set App = Nothing
                Exit Sub
            End If
            
            'Create the AVDoc object.
            Set AVDoc = CreateObject("AcroExch.AVDoc")
            
            'Check if the object was created. In case of error release the objects and exit.
            If Err.Number <> 0 Then
                MsgBox "Could not create the AVDoc object!", vbCritical, "Object Error"
                Set AVDoc = Nothing
                Set App = Nothing
                Exit Sub
            End If
            
            On Error GoTo 0
            
            'Open the PDF file.
            If AVDoc.Open(PDFPath, "") = True Then
                
                'Open successful, bring the PDF document to the front.
                AVDoc.BringToFront
                
                'Use the FindText method in order to find and highlight the desired text.
                'The FindText method returns true if the text was found or false if it was not.
                'Here are the 4 arguments of the FindText methd:
                'Text to find:          The text that is to be found (in this example the TextToFind variable).
                'Case sensitive:        If true, the search is case-sensitive. If false, it is case-insensitive (in this example is True).
                'Whole words only:      If true, the search matches only whole words. If false, it matches partial words (in this example is True).
                'Search from 1st page:  If true, the search begins on the first page of the document. If false, it begins on the current page (in this example is False).
                If AVDoc.FindText(TextToFind, False, True, True) = True Then
        
                    'Text was not found, close the PDF file without saving the changes.
                    AVDoc.Close True
                    
                    'Close the Acrobat application.
                    App.Exit
                       
                    'Release the objects.
                    Set AVDoc = Nothing
                    Set App = Nothing
                    
                    'Inform the user.
                    Cells(i, 3).Value = "Text is found in the PDF file"
                    
                Else
                    
                   
                    
                     'Text was not found, close the PDF file without saving the changes.
                    AVDoc.Close True
                    
                    'Close the Acrobat application.
                    App.Exit
                       
                    'Release the objects.
                    Set AVDoc = Nothing
                    Set App = Nothing
                    
                    'Inform the user.
                    Cells(i, 3).Value = "Text not found in the PDF file"
                
                End If
                
            Else
                
                Application.Wait Now() + TimeValue("00:00:05")
                Application.SendKeys ("~")
               
                'Unable to open the PDF file, close the Acrobat application.
                
                App.Exit
        
                'Release the objects.
                Set AVDoc = Nothing
                Set App = Nothing
                
                'Inform the user.
                Cells(i, 3).Value = "Could not open the PDF file!"
                
                
                End If
        
        Next i
        
    End Sub

    So when one starts executing this command by command, the following happens. You get to this:

    'Open the PDF file.
            If AVDoc.Open(PDFPath, "") = True Then
    Acrobat tries to open the PDF file, but it is a corrupted (non-PDF) file, Acrobat dialog box pops up, VBA freezes since someone has to click on Acrobat and click OK on the dialog box that says the file is corrupted, then VBA resumes with the code. This is the drama.

  21. #21
    Forum Guru Kyle123's Avatar
    Join Date
    03-10-2010
    Location
    Leeds
    MS-Off Ver
    365 Win 11
    Posts
    7,238

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    I meant for downloading the pdfs.

  22. #22
    Registered User
    Join Date
    04-28-2013
    Location
    Stockholm
    MS-Off Ver
    Excel 2007
    Posts
    93

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    Cannot post my code for some reason.

  23. #23
    Registered User
    Join Date
    04-28-2013
    Location
    Stockholm
    MS-Off Ver
    Excel 2007
    Posts
    93

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    "Sucuri WebSite Firewall - CloudProxy - Access Denied"

  24. #24
    Forum Guru Kyle123's Avatar
    Join Date
    03-10-2010
    Location
    Leeds
    MS-Off Ver
    365 Win 11
    Posts
    7,238

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    Try sticking it in a .txt notepad file and attaching it to the post

  25. #25
    Registered User
    Join Date
    04-28-2013
    Location
    Stockholm
    MS-Off Ver
    Excel 2007
    Posts
    93

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    download_files_macro.txt

    So here it is.

    I name my files "whatever.pdf" from the onset and supply to the macro like this. If I don't, code just downloads files with no specific format specified. Otherwise, works pretty fine.

  26. #26
    Forum Guru Kyle123's Avatar
    Join Date
    03-10-2010
    Location
    Leeds
    MS-Off Ver
    365 Win 11
    Posts
    7,238

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    I've made a function so you can keep most of your code intact:
    Function DownloadPDFToFile(url As String, filePath As String) As Long
    
        
        Static request As Object
        Dim ret As Long
        Dim fileType As String
    
        ret = 1
        If request Is Nothing Then Set request = CreateObject("winhttp.winhttprequest.5.1")
        With request
    
            .Open "GET", url, False
            .send
            
            'Get the MIME filetype
            extension = .getresponseheader("Content-Type")
            
            'Does the file-type contain "pdf" - if so save it
            If InStr(1, LCase(extension), "pdf") Then
                Dim stream As Object: Set stream = CreateObject("ADODB.Stream")
                stream.Type = 1
                stream.Open
                stream.write .responsebody
                stream.SaveToFile filePath, 2
                ret = 0
            End If
        End With
        
        DownloadPDFToFile = ret
    
    End Function
    You should just then be able to change:
                'Save the files to the selected folder.
                'Result = URLDownloadToFile(0, Cells(i, 3).Value, filePath, 0, 0)
                Result = DownloadToFile(Cells(i, 3).Value, filePath)
    It's a bit difficult to test since I don't have your data, but if you upload a workbook, I'd be happy to
    Last edited by Kyle123; 05-06-2015 at 11:28 AM.

  27. #27
    Registered User
    Join Date
    04-28-2013
    Location
    Stockholm
    MS-Off Ver
    Excel 2007
    Posts
    93

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    Thank you very much for the suggestion, Kyle! I would definitely try it.

    I have finally found a way to overcome this obstacle even if it's done outside VBA. I came across a great programme that checks if PDF files are corrupted/genuine and deletes them straightaway if not. This does the job for me. I'd mark this thread as solved. Thank you once again for your immense help and kindness.

  28. #28
    Valued Forum Contributor fredlo2010's Avatar
    Join Date
    07-04-2012
    Location
    Miami, United States
    MS-Off Ver
    Excel 365
    Posts
    762

    Re: Close Acrobat from VBA if it tries to open a corrupt file

    Hello,

    I have been looking for something that would allow us to check if the file is corrupted but no luck

    http://help.adobe.com/livedocs/acrob...ccessible=true

    lol crazy

    I found something for a method "AVDocOpenParams" but apparently its not exposed through VBA

    Apparently the last option ASBool suppressDialogs; would allow you to suppress any dialog thus solving our problem.

    Thanks

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Corrupt file. Fail to open using the workbooks.open method
    By Mortphi in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 06-27-2013, 01:48 AM
  2. Open 2nd file(CSV) from cell reference, copy columns to main file & close 2nd file
    By Langchop in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 01-31-2013, 05:09 AM
  3. Reliable way to open PDf, copy contents and paste it to Excel
    By Snoopy2003 in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 08-13-2012, 05:44 PM
  4. How to: Open file, format data, save file, close file and repeat.
    By thexeber in forum Excel Programming / VBA / Macros
    Replies: 5
    Last Post: 09-11-2010, 12:56 PM
  5. Close Adobe Acrobat from Excel
    By quartz in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 02-16-2005, 09:40 AM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1