Bypassing a website's Security Certificate warning using VBA - excel

I access a website through VBA. This website has a security certificate.
Is there a way to get through this warning and go straight to the webpage.
Sub Certificate()
Dim IE As Object
Set IE = CreateObject("InternetExplorer.Application")
With IE
.Visible = True
.navigate ("Website URL")
While IE.ReadyState <> 4
DoEvents
Wend
{Application.Wait (Now + TimeValue("0:00:05"))}--Optional
'This is the security certificates webpage HTML
'This clicks the not recommended but continue to website button
IE.document.getElementsByName("overridelink").Item.Click
End With
End Sub
When I execute this code this line:
IE.document.getElementsByName("overridelink").Item.Click
gives me a
Runtime error '91'
This code works when the security certificate warning pops up however it doesn't always pop up and goes straight to the website, giving me that error.
I've gone into internet options and unchecked everything that would cause that warning as well as adding it to trusted site.

CAUTION! Use sparingly!
If the only time you get an error with the line IE.document.getElementsByName("overridelink").Item.Click is because you don't need it, you can use this:
On Error Resume Next
IE.document.getElementsByName("overridelink").Item.Click
On Error Goto 0
instead of:
IE.document.getElementsByName("overridelink").Item.Click
CAUTION! Read this:
Make sure to include the On Error Goto 0 line directly after the section you want the error ignored on, as that line resets the error-behavior to default. Otherwise, the On Error Resume Next will mask any and all other errors in the code following it. This can cause HUGE issues with code giving unexpected results for no apparent reason and/or attempts to troubleshoot problematic code.
Another issue: if the error-skipping enclosed code goes wrong for an unexpected reason, you won't have any way of catching this unless you set-up a more elaborate error catching section in your code.

Related

Bypassing/ignoring corrupt Excel files

I have to loop through Excel files stored in a folder and process them using VBA. I want to only process those Excel files that open without any questions being asked (questions like unreadable content, corrupted file, unknown source etc).
Is there some way to do this? I have tried On Error go to Label, but the problem still persists with some files.
That sounds weird. You didn't post any sample code, but you can try it like this.
Sub t()
Application.ErrorCheckingOptions.BackgroundChecking = False
On Error Resume Next
'other code here
On Error GoTo 0
Application.ErrorCheckingOptions.BackgroundChecking = True
End Sub
Normally, 'On Error Resume Next' is not recommended, because it will hide all kinds of errors from your view, which can be quite helpful for debugging issues, but in this case it may be appropriate.

VBA Selenium Chrome Unexpected Alert Error

I am currently using Selenium, VBA Excel, and Chrome to scrape information from a site. Everything works fine until one of the values from my list is not available on the site, then I get a Run-time error '26' UnexpectedAlertOpenError. Error image.
I have added this line Chrome.SwitchToAlert(5).accept to handle the error which works when the value is not available. Unfortunately, adding that line returns a Run-Time error '27' NoAlertPresentError when the value from the list is available. Error image.
The error messages make sense, can't act on what is not there. I need a way to check if there is an alert and if so then quit chrome, else run the rest of the code. I have tried If Chrome.FindElementsByTag("tr") Is Nothing Then Chrome.SwitchToAlert(5).accept else and If Chrome.FindElementsByXPath("//*[contains(text(),'Details')]").Count > 0 Then and other things but nothing seems to work to address the error 26.
Well so based on the VBA selenium library I checked apparently there is no way of checking a count of the alerts already displayed, something we could do for browser windows by using:
driver.Windows.Count 'driver being the variable used to refer to an instance of Chromedriver
So the solution I am using is of wrapping the entire selenium code between error handlers:
On Error Goto Problem:
' Your code over here
''''''
''''''
On Error Goto 0
Exit Sub
Problem:
If InStr(1, Err.Description, "Alert") <> 0 Then
driver.SwitchToAlert.accept 'could also use: driver.SwitchToAlert.dismiss
Resume Next 'resumes code from the next line in code that threw error
End If
This way I believe whenever any sudden unexpected alert pops up, the error handler will accept/dismiss the alert and with 'Resume Next' ensure program moves on from the next line

How to SaveAs with OneDrive while offline?

I use VBA to create copies (Excel and PDF) of an Excel document.
I save in the OneDrive folder (C:\Users\XXX\OneDrive) so I can access the document from every device later. I use this folder so I can save while I am connected to internet or not.
When I am connected to internet and OneDrive everything works.
When I am not connected to internet I get
error 1004 method saveas of object _workbook failed
My macro stops but when I go to the folder the files are there.
I get the error on:
ActiveWorkbook.SaveAs Filename:=Fname, FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
(Fname="C:\Users\XXX\OneDrive\YYY\ZZZ.xlsm")
I couldn't find anything related to this function not working on OneDrive while not connected to internet.
If your file is in OneDrive, I would first make sure to deactivate the AutoSave feature. I've personally had some bugs with it in the past, so it might help.
I'm not aware of this particular bug that you are experiencing, but since you are saying that the file is actually saved properly even if an error is triggered, there is a way to ignore the error and check if the file was actually saved. It would look a little like this:
Const RETRY_LIMIT = 2
Dim DoesFileExist As Boolean
dim RetryCounter as Integer
Do While RetryCounter < RETRY_LIMIT And DoesFileExist = False
On Error Resume Next
ActiveWorkbook.SaveAs Filename:=Fname, FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
On Error GoTo 0
DoesFileExist = FileExists(Fname)
RetryCounter = RetryCounter + 1
Loop
If DoesFileExist = False Then
MsgBox "Error: File couldn't be saved."
Exit Sub
End If
Note that I've added a retry limit of 2 to make sure that we don't go into an infinite loop.
Also make sure to add the following function in the module you are working on to make sure the code above works.
Function FileExists(ByVal FullFileName As String) As Boolean
If Dir(FullFileName) <> vbNullString Then FileExists = True
End Function
Some explanations and caveats
If you have never used error handling statements such as : On Error Resume Next or On Error GoTo 0, I would strongly advise you to have a look at C. Pearson's Error Handling In VBA article.
To summarize, what On Error Resume Next does is simply ignore the error and let the code handle the error. In our case, the DoesFileExist does the job of making sure that the code ran without error and the if statement after the loop will make sure to stop the code if all tentative to save the file failed. This does the job, but you could also check Err.Number to handle different type of error as well.
Regarding On Error GoTo 0, to put it simply, it resets the VBA error handling to its normal state where any error will launch the usual run-time error dialog box
I ended up saving the file on my desktop and then using FileSystemObject to move the file. It works fine except that if I try to open the file right away (using VBA or directly in windows explorer) I get a network error. If I wait about 1 min I don't get that error anymore. So I decided to live with it for now.
here is an example:
Dim FSO as Object
Set FSO = CreateObject("Scripting.Filesystemobject")
FSO.MoveFile("SourceFileName", "TargetFileName")
Thank you very much for your help

Runtime Error with Workbook Auto Open + MsgBox as response for an user

I was trying to put MsgBox into my code. It should be shown only if call Table.auto_open doesn't work.
In my final document are few of those Call statements and i would like to get only that msgbox, if one or few of Call statements doesn't work.
For Example "Auto_open" will be changed to "auto_op" what naturally won't be possible, because in real sheet it is "Auto_open".
Or in another example that code from "Auto_open" is broken.
I need some help with that. It's seems to be simple, but I think it's not possible to put that "On Error GoTo" code in that place just like that, because Call doesn't give me a real error?
Can someone say me what I'm doing wrong? I tried already all combinations of that Error handling, nothing works.
Private Sub Workbook_Open()
On Error GoTo Error
Call Tabelle1.auto_open
Exit Sub
Error:
MsgBox "Failure"
Resume Next
End Sub
If you are calling a sub that does not exist you will get a Compile Error.
You can check for these errors by going to VBE>Debug>Compile VBAProject (or just try to run the macro)
Compile Errors, much like Syntax Errors, have to be handled before you can run a sub. Thus, these errors cannot be handled with code such as On Error GoTo EH or On Error Resume Next as these are only activated once the sub is actually running.
You can convince yourself of this by producing a common Compile error, or Syntax error, and trying to step through the code (F8). You will notice that the error occurs on your Sub [Name] () line, which indicates that you never actually entered your sub before the error occurred. Thus, you can intuitively see that your error handler will never actually be activated, resulting in an error message being displayed.
Once you have accounted for all Compile/Sytax Errors, you can check out this link, which will explain how you can handle Run Time Errors when you are calling other sub procedures from a sub.

Alternate message when VBA can't open file

I have a VBA script that when the user executes it, it opens and writes new data to another file on a Network share drive. Occasionally the script can't access this file to write new data to it because someone else is simultaneously trying to open it (via read only through a VBA script that they have).
This particular file opening error is not caught in the error handling code and a box comes up and asks the user to End or Debug. Is there a way to bring up an alternate popup box that says something like "Could not process request. Please wait a few seconds and try again."
yes. put in error handling around the file opening code. like this:
on error goto FileError
'file opening code
on error goto 0
exit sub
FileError:
msgbox("Could not process request. Please wait a few seconds and try again")
basically, the OnError tells everything after that statement to do whatever you specify in the event of an error. in this case I've put goto FileError so if an error is encountered anywhere after the onError processing will stop and go to the line marked FileError.
then the OnError goto 0 disables that error handle. that way if other code generates an error it wont be handled by the FileError handle. the other option for onerror is OnError Resume Next which makes the program skip over code that generates an error. so it wont throw the error, and it will just continue processing.
Note the: Exit Sub before the FileError label, that way the code wont go into the FileError label unless it is sent there by an error being generated.

Resources