Cannot Run Visual Basic Editor Because of a Syntax error on Application.Calculate - excel

I have a VBA Excel model which I have separated into two separate workbooks:
InputsWB, which contains all the inputs for the model, and
RunnerWB, which contains the bulk of the VBA code (and all the class modules live here).
Depending on the needs of the user, the InputsWB can either call the macro in the RunnerWB or the RunnerWB can call multiple versions of the InputsWB. The detail doesn't matter for this question but the two workbooks need to be separated.
Mysteriously, after the split I sometimes get a Run-time 1004 error with the message Cannot Run Visual Basic Editor Because of a Syntax error. If I Debug + F5 then the code runs until it encounters the next Application.Calculate.
I have seen many similar questions while recording macros, or on Application.Calculate. I think mine is related to the Application.Calculate, but those answers don't explain why this happens. Some reasons I can think off, but cannot confirm online is:
There are Modules in the two workbooks with the same names (although I've changed the modules names in the InputsWB but still get the error on occasion.
There are VBA functions in the two workbooks with the same names
Are there any other reasons why I could be getting these errors?
UPDATE (2019/12/02)
I finally realised why I got this error. I am calling a macro in my RunnerWB from my InputsWB. However, there was a duplicate function declared in my RunnerWB. Usually, this would give a Compile error: ambigious name detected when the macro was initiated from ThisWorkbook. However, because it was initiated from another workbook I got the Syntax error explained above.
UPDATE (2020/07/22)
I am now getting this error again on Application.Calculate right at the end of the run. Which breaks me is that I use Application.Calculate many times during the run.
UPDATE (2020/07/23)
I found the issue that caused the bug at last.
I had a sub called Main in a Module called Main
One of the buttons in my workbook referred to this button, and because the names are the same it links it as Main!Main
Later I renamed the module to MainSub. The button still worked, but something inside VBA was broken which was triggered in some Application.Calculate executions.
Conclusion
Never give your sub the same name as your module in VBA, as this may cause problems down the line.

Related

Name conflict error pops when creating reference at runtime, but not at design time

I'm having this staggering problem in creating a reference at runtime.
In short: I have an addin referenced in another addins, all created by myself and all working fine (except for some annoying popup which appears on loading Excel). As a workaround to this annoyance, I removed the existing reference to create it later, at runtime. But when I try creating the reference, it returns an "Name conflicts with existing module, project, or object library" error popup, and the reference is not created--which makes no sense, because if I create the reference at design time it works perfectly. There is no module or project with repeated name.
Now explaining a little further.
I have four kinda-complex Excel applications I'd had developed for my job. Each one is a VBA project, distributed as Excel Addins (.xlam).
Additionally, I have a fifth project with functions common to the other four. This fifth project is referenced in the other ones (via Tools -> References). So now, all I have to do is to call them as any API outside referenced function (commonProject.Function (arg1, arg2, arg3 etc)).
Unfortunately, I had some problems with a popup message (here) and the workaround seems to be referencing the fifth project in the other ones at runtime.
In order to do this, I uninstalled three of the other four Addins, remaining only one, and used the following code in its Workbook_Open event:
Private Sub Workbook_Open()
Dim strNamePath As String
Dim bolAddinIsRefered as Boolean
Dim oRef As Variant
strNamePath = "c:\etc\etc\etc\Filename.xlam"
For Each oRef In ThisWorkbook.VBProject.References
If oRef.FullPath = strNamePath Then bolAddinIsRefered = True
Next oRef
If bolAddinIsRefered = False Then ThisWorkbook.VBProject.References.AddFromFile strNamePath
End Sub
The problem is, when I used to create the reference at design time by hand, it worked mostly fine (except for the annoying popup I'm now trying to circumvent). But when I try creating the Reference at runtime, it returns an "Name conflicts with existing module, project, or object library" error popup, and the reference is not created.
I have verified the module and worksheet names and there is no duplicated one.
Does anyone have any idea how to prevent this error?
it seems after one and a half day struggling with a problem, when you ask the question on StackOverflow the solution just pops in your mind.
I'd already tried to change both projects names, even internal functions or subs resembling the same name. But I had not looked upon the FILE NAME!
As my solution is called Sisyphus, the filenames of all addins started with "Sisyphus"--"Sisyphus Common Functions.xlam", "Sisyphus DocMerge.xlam" etc.
The problem was VBA was comparing the first word in filename. I removed spaces and it worked well. Now my filenames are "SisyphusCommonFunctions.xlam", "SisyphusDocMerge.xlam" etc. and the referencing in runtime works all right.
Thank you for your time, I'll let this Question and Answer here, because it can be usefull to someone.

MS Office last updates causing some strange behavior in handling VBA code

Our admins ran some MS Office 2016 updates (Build 11929.20838) and all of a sudden I noticed a few unexpected errors in one of my previously written Excel VBA macros. For example below error is popping up against any variable which I have not defined explicitly. It was not the case before and unless I had mentioned Option Explicit, I had never experienced anything like this.
Compile error:
Can't find project or library
I am also getting the same error against the following 2 statements of my code, whereas it used to run smoothly before the last Microsoft Office 2016 update.
' Against the following two declarations, the compiler is highlighting
' Date in parenthesis and quoting same error "Can't find project or library"
xMonth = VBA.DateTime.Month(Date)
xYear = VBA.DateTime.Year(Date)
' And showing same error as above against defining an Array variable like below
srchString = Array("invoice_number", "invoice_date", "Category_wise_code", "Bill To Customer", "consignees_address_long")
'And even here, it is giving the same error:
[A1].Font.Bold = True
Does anyone have any idea about these errors and how to resolve this issue? All of this quite unexpected. Let me tell you this macro has been in my use for over 4 years and I never ran into issues like these.
You will find something fishy here:
https://www.google.com/search?rlz=1C1CHZL_enGB838GB838&ei=EOInX-ibPMeusAXFw7z4Cg&q=%22ms+office+2016%22+%22july+updates%22+%22VBA%22&oq=%22ms+office+2016%22+%22july+updates%22+%22VBA%22&gs_lcp=CgZwc3ktYWIQAzoECAAQRzoICCEQFhAdEB46BQghEKABUOTJCljq_gtgg4UMaABwAXgAgAHzAogByiiSAQYyLTIuMTSYAQCgAQGqAQdnd3Mtd2l6wAEB&sclient=psy-ab&ved=0ahUKEwjo4_6J5f7qAhVHF6wKHcUhD68Q4dUDCAw&uact=5
Although not all links are opening, but Google window is briefly showing that some people are also facing macro crash situation.
Thanks for your time reading my post.

Error accessing file. Network connection may have been lost

So I am using VBA code to open a Excel file, and download data into the worksheet that contains the code.
It worked, now I get the error:
Error accessing file. Network connection may have been lost.
I opened the code to see where it is falling. (I thought maybe the file has changed location or the name has been changed.) When I go through the code (using F8), I immediately get the error on the first line of code (SUB TITLE) and it is marked yellow.
"Error accessing file. Network connection may have been lost"
This (and other generic error messages) can be thrown when the VB Editor detects a discrepancy between the source code (the text you see in the editor) and the compiled binary 'p' code also saved in the workbook. This discrepancy situation is commonly referred to as a "corrupt" workbook.
A temporary fix is to export the modules, forms, and classes one by one, create a new workbook and import them back in. At this point you can now at least edit your source code in order to address the root cause.
However, if the root cause of the corruption is not dealt with in your source code, then whenever the VB Editor next runs/compiles the troublesome portion of your code the corruption in the compiled binary 'p' code will be reintroduced.
This corruption will become apparent only once you have saved and reopened the workbook, at which point the VB Editor will detect the discrepancy between the source code and the binary 'p'code saved in the workbook and throw the error once again.
My solution on the following post gives insight into one such cause of this error due to inadvertently creating a circular dependency in classes that use the IMPLEMENTS statement:
IMPLEMENTS circular dependency issue

Cannot run common module in xlam file as macro is disabled

VBA / Excel - 2007
I want to create one (possibly many) .xlam file(s) to hold common modules accessible across projects. Along the way I have received a number of errors but through the creation of a "mickey-mouse" scenario I have boiled it down to one error condition (as shown in actual result):-
I have seen several problems reported here related to this which in the end have either not been answered or the solution has not quite hit the mark
As a precursor to this I was able to put my common module into another .xlsm project and successfully execute it by using a reference to that called project. However it would be preferable not to create a workbook for the sole purpose of housing common modules
'Caller VBAProject (Caller.xlsm):
Public Sub Caller()
Dim i As Integer
i = 0
'*** Error in line below***
Application.Run "C:\Users\IT\AppData\Roaming\Microsoft\AddIns\Common.xlam!Test", i
End Sub
'Called Test (Common.xlam) -- different project, obviously
Function Test(ByRef i As Integer) As Boolean
If i = 0 Then
Test = False
Else
Test = True
End If
End Function
Actual Result
Run-time error '1004':
Cannot run the macro
'C:\Users\IT\AppData\Roaming\Mirosoft\AddIns\Common.xlam!Test'
The macro may not be available in this workbook or all macros may
be disabled.
Steps Undertaken (in Excel Options)
Trust Center
a) Macro Settings
-- both i) and ii) (at different times)
i) Disabled all macros with notification
ii) Enabled all macros
iii) set Trust access to the VBA project object model
b) Add-ins -- left as default ie no option ticked
c) Trusted Locations -- have added the following
C:\Users\IT\AppData\Roaming\Microsoft\AddIns\
Add-Ins
As an Active Application Add-in I have
C:\Users\IT\AppData\Roaming\Microsoft\AddIns\Common.xlam
Can anybody please tell me what I might have missed?
So just to summarise I don't have a direct answer to my question thus far, that is how to avoid the 1004 error when calling a macro within a .xlam file. However, I do have a more than adequate alternative which is to import the common file into a different module within the same project. What I'm realising is that as I write this it isn't an import at runtime or late binding as Zac implied. I'm not sure I'm too worried though (at least at the moment).

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