How do I find host specific 1004 Descriptions - excel

I am working on a language- (English, German, French, ...) and host (Excel, Word, PP, Access, ...) agnostic VBA-Error handling, and reporting system (using Excel as my VBA development platform).
Lately, I was trapping a VBA 1004 error coming up with an Err.Description I never "saw" until that date. Until now, I spent some hours, hopefully not waisted, to explore what's behind that "magic" 1004 error number.
The best general explanation I found so far (including Microsoft's domains) was:
Quote>>> Error 1004: Application-defined or object-defined error. This is a very common catch-all error message. This error occurs when an error doesn’t correspond to an error defined by VBA. In other words, the error is defined by Excel (or some other object) and is propagated back to VBA. << VBA Error Codes
So, my question is:
Is there a native VBA way to get this host-specific
(Excel/Word/PP/...) 1004 error messages? (I am pretty sure, there
isn't)
Or, is there a place on the internet that list them all, these host-specific Descriptions (and I was only to drunk to google it ;-)
Or, do you know any Office resource file(s) (DLL/EXE/whatever format) that I might look inside to find the Err.Descriptions strings I'm looking for?
BTW, I'm an experienced developer - you do not have to explain anything to me, but just tell me, if you know ;-)
These are my findings, so far:
The VBA's error# 1004 is a dummy/placeholder error assigned a generic, internationalized(!) descriptional text depending on the ERROR_CONTEXT.
A real ERROR_CONTEXT related error only exists at RUNTIME and it must deal with a real specific error. That is, we CANNOT create a specific #1004 Err.Description from within our immediate window typing something like so: Error 1004 {enter}
This only echoes the default err.description.
The ERROR_CONTEXT always depends on the VBA host we are in while executing our code. Thus, the textual Err.Description never clashes between different hosts. BUT, the Err.Number does as it always is 1004.

Related

Is there a way to check if a connection in Excel is valid before refreshing it?

Quick Background:
I have almost no experience with VBA. I started learning this two weeks ago and have made fast progress, but I am lacking a lot of knowledge. I do not know enough to know what I do not know, for lack of a better word. My apologies up front if this is a question that has a very simple solution. I have been scouring Microsoft's VBA documentation with no luck for several days now.
The Problem:
I have a single connection in a main spreadsheet to a spreadsheet on SharePoint that pulls data from inputs by operators on their cell phones. The current way my code is set up, it will refresh that connection before running calculations to ensure that any new data is accounted for.
However, since the connected document's location (or even name) may change in the future due to it being a shared document, I wanted to find a way to test that the connection was valid; i.e. that the correctly named file existed where it was supposed to be.
Currently, if the file name or location do not match, Excel throws an error and my code will stop running. Ideally I would like to have something similar to this:
If connectionIsValid Then
Refresh the connection
Else
MsgBox "Could not refresh connection", vbInformation
*Continue with code instead of throwing an error*
End If
I have tried things like:
If ActiveWorkbook.Connections(1).OLEDBConnection.IsConnected Then
Run Code
End If
But after reading the documentation I realized the above is related to the MaintainConnection Property being true.
and:
On Error GoTo ErrorHandler
*Refresh the sheet*
*Continue code*
Error Handler:
*Don't refresh the sheet*
*Continue code*
Any help or even a pointer in the right direction is greatly appreciated. Thank you for your time.
I'm not sure what is wrong with your second suggestion - using an error handler.
Function checkConnection()
On Error GoTo errorHandler
ActiveWorkbook.Connections.Item(1).Refresh
Exit Function
errorHandler:
MsgBox "Could not refresh connection. " & Err.Description
End Function
I've just added the Exit command there, otherwise it will run the code in the errorHandler label every time, even if there isn't an error.

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.

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

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.

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.

Errors Raised within Class Debug As If Raised at Property Call

I am (unfortunately) developing an application in Excel 2000 VBA. I believe I have discovered that any error raised within a Custom Class property, function, or sub debugs as if the error were raised at the point in the VBA code where the property is called. That is, the VBE debugger does not take me to the point in the Class property where the error occurred, but instead where the property was first entered (from a Module Sub or Function, e.g.) This makes it frustrating to develop anything more than the most shallow OO Excel 2000 VBA code since I have to step line-by-line through every Class method to discover the instructions causing an error.
Am I missing something or is this a known bug I have to deal with in Excel 2000? Has this been fixed in 2003 or 2007?
Example code:
'''''''''''''''
'In Module1:
Public Sub TestSub1()
Dim testClass As Class1
Dim testVariant As Variant
Set testClass = New Class1
testVariant = testClass.Property1 'Debugger takes me here...
End Sub
''''''''''''''
' In Class1
Property Get Property1() As Variant
Err.Raise 666, , "Excel 2000 VBA Sux!" 'But error is actually thrown here.
End Property
For Office 2003 you will get this behaviour when the debugger is configured to break on unhandled errors (the default configuration).
If you want it to break on the Err.Raise line, you need to configure it to break on all errors (Tools/Options/General/Error Trapping/Break on All Errors).
I believe it's the same for Office 2000 but don't have a copy to check.
This page is a very good resource on error handling in VBA:
Error Handling and Debugging Tips and Techniques for Microsoft Access, VBA, and Visual Basic 6
This "feature" is the same in Excel 2003 and I'd be surprised if it's different in 2007.
The same still holds true in Excel 2010 - that's where I met this behaviour.
To quote Chip Pearson's site:
There is absolutely no reason to use an error trapping setting other than Break In Class Module.
His description of the difference between the error modes:
When you are testing and running your code, you have three error trapping modes. The first is Break On All Errors. This will cause the debugger to open if any error occurs, regardless of any On Error handling you might have in the code. The second option is Break On Unhandled Errors. This will cause the debugger to open if the error is not handled by an existing On Error directive. This is the most often used option and is the default setting. The third option, Break In Class Module is the most important and least used. It is not the default error trapping mode, so you have to set it manually.
The Break In Class Module is the most important because it will cause the debugger to break on the line of code within an object module that is actually causing the problem. The Break In Class Module setting is in the Options dialog accessible on the Tools menu. It is on the General tab of the Options dialog, as shown below.

Resources