VBA Excel code stops execution after adding a worksheet - excel

I seem to have stumbled upon a problem I can't seem to figure out how to solve. I'm currently working with 2 separate workbooks, one of them is the active workbook the code is run from, the other one is a separate workbook I need to open:
On Error GoTo ErrorHandler:
Set manWb = ActiveWorkbook
Application.AutomationSecurity = msoAutomationSecurityForceDisable
Set conWb = Workbooks.Open(PARDirOTC & PARFileOTC, ReadOnly:=False)
Application.AutomationSecurity = msoAutomationSecurityByUI
ActiveWindow.Visible = False
On Error GoTo 0
I set the AutomationSecurity to msoAutomationSecurityForceDisable to prevent that second workbook from running its Workbook_Open event, which has code in it I don't need in this situation. That error handling event never seems to activate, and the code keeps going without issues.
Everything works nicely from this point on, I gather and exchange data between these 2 workbooks and nothing seems to go wrong. That is, until it gets to the point where I need to create a worksheet on the second workbook, the one called "conWb".
Set conOT = conWb.Sheets.Add(After:=conWb.Sheets(conWb.Sheets.Count))
This is the troubling line. The worksheet is created, but the code suddenly stops executing at this point. No error message at all, nothing pops up, it simply stops. I've noticed that the code apparently stops executing, and switches to the code in the newly created sheet, which is blank and has nothing in it. I can't understand why.
I've looked around, other people seem to have found similar issues, but none of their solutions worked for me. I've tried playing around with several Application settings, like EnableEvents, ScreenUpdating, AutomationSecurity, etc, but nothing works. Along the code, I've also tried to remove or comment out all of the "On Error" events, fearing that they could be hiding an error that could explain this behaviour, but it doesn't seem to be the case.
I'll highly appreciate if someone with more experience than me could help figure out what could be the reason for this behaviour. Thanks in advance.
Kind regards

Using Application.EnableEvents instead of Application.AutomationSecurity when opening the second workbook, like one of you suggested, ended up solving the entire issue. Like so:
On Error GoTo ErrorHandler:
Set manWb = ActiveWorkbook
Application.EnableEvents = False
Set conWb = Workbooks.Open(PARDirOTC & PARFileOTC, ReadOnly:=False)
Application.EnableEvents = True
ActiveWindow.Visible = False
On Error GoTo 0
As far as I know, AutomationSecurity can be used to disable all macros when opening a workbook programatically, and I thought that would be enough to prevent the Workbook_Open event, but I'm assuming that either there's some other event I wasn't aware of, or the AutomationSecurity setting works in a different way than what I initially thought.
Either way, the problem seems to be solved, so thank you.
Kind regards

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.

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

Macro gives error when updating connections - but only sometimes

My macro opens up a couple of files, then updates Connections in one of those files. These connections are all pulls from website html tables. The macro worked just fine for a while. Now, when I run the macro, I get this error:
Run-time error '1004':
Application-defined or object-defined error
When debugging, the error points to the first connection update line of the macro (Advanced2). Here's the code:
Workbooks.Open (ThisWorkbook.Path & "\TheFormulaFinal V5.xlsm")
Workbooks.Open (ThisWorkbook.Path & "\WebScraper.xlsx")
Windows("WebScraper.xlsx").Activate
ActiveWorkbook.Connections("Advanced2").Refresh
ActiveWorkbook.Connections("DVP").Refresh
ActiveWorkbook.Connections("PrSolu").Refresh
ActiveWorkbook.Connections("Misc").Refresh
ActiveWorkbook.Connections("NF Project").Refresh
ActiveWorkbook.Connections("OppTot").Refresh
ActiveWorkbook.Connections("PlrTot2").Refresh
ActiveWorkbook.Connections("TeamTot").Refresh
ActiveWorkbook.Connections("RotoGuru").Refresh
Sheets("PlrTot2").Select
However, the very odd thing is that if I close the two files my code opened (WebScraper and TheFormula V5) without saving, then run the exact same macro, the next time it works! I suspect it has to be some kind of time-related error. I have turned off all background connection refresh as well as any kind of refresh upon file open, so none of these connections should ever update unless they are manually called to do so. I tried using Application Wait to add some time after the WebScraper file opened, and/or after the first refresh, but no avail. I also tried adding some dummy activities after the WebScraper file is activated to see if the file needed some time to load the connections, but also no luck.
Any help is appreciated, thanks!
Workbooks.Open function returns reference to opened workbook. You can use this reference instead ActiveWorkbook.
Dim wb As Workbook
Set wb = Workbooks.Open(ThisWorkbook.Path & "\WebScraper.xlsx")
wb.Connetions("Advanced2").Refresh
...

msoFileDialogFilePicker resulting in error

Please don't comment with anything about naming conventions, approaches, asking what the code is supposed to DO, or anything that isn't directly related to my issue:
This runs perfectly for me, everytime--A window pops up, and I select multiple Excel files and their data is uploaded into my sheet (Code not pictured). My client says he gets an error when he runs it, and naturally I assumed it was because he ran it on a Mac...but he says he gets the error on both PC and Mac. I can't recreate the error...and here we are.
Here's the code in question, the erring line highlighted in yellow:
Code for your copying:
Sub Import_Employee_Sheet()
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = True
If .Show = True Then
End If
End With
End Sub
This is probably because he hasn't set the Microsoft Object [Version number] Library reference under Tools/References in the IDE, or because it's broken. Also see this post on how to fix the problem WITHOUT setting the object reference in order to avoid similar problems in the future.
Edit
It should read "...without setting the library reference" above.

Err.Number not populating for 'Excel Ran Out of Resources' error

I've developed a program using Excel VBA which occasionally causes an 'Excel Ran Out of Resources' error.
Closing the file, reopening, and rerunning the macro always fixes whatever issue created the error. I know that preventing the error in the first place is best practice, but am resigned to believe that it's unavoidable.
So, I would like to alert the user of the error, instead of Excel doing it, and perform some actions once the error has been detected. The problem is that I can't get VBA to recognize the error using the On Error GoTo ErrorHandler routine or the Err.Number property. I never get to the msgbox below:
My code is as follows:
Sub test()
On Error GoTo ErrorHandler
Calculate
ProcedureDone:
Exit Sub
ErrorHandler:
MsgBox "Error", vbOKOnly, "Oops"
Resume ProcedureDone
End Sub
Any insight would be fantastic since I've been searching for several days and haven't been able to find a work around.
I just happened to run across another issue that sounds like yours.
The point from the other thread is that Excel does not treat these application method results as VBA errors. Rather, they are Excel alerts, and they can be suppressed but not trapped in VBA as errors.
The way I interpret this is that when you execute certain application methods from VBA, it does not raise errors that VBA can trap. Rather, Excel interacts with the user as if the user had issued a GUI command. On the other hand, if an application method is designed to interact with VBA (e.g., if it returns a value), then VBA might be able to handle its errors.
This is distinct from the way VBA handles worksheet functions rather than application methods. VBA can intercept errors raised by worksheet functions, as noted in "Error Handling With Worksheet Functions" here.
I realize this does not solve your problem, but it gives you an idea of why.

Resources