MS Access VBA editor activity affects running program variables - vba

MS Access 2016 running on Windows 10.
I am debugging VBA changes to a MS Access application and am seeing some unexpected interactions between the VBA editor and running code. The steps are basically:
Open the application, which opens startup form.
The startup form_load instantiates an object used by other forms the user may subsequently open.
Open the VBA editor
Using the VBA editor, select a line in any code module and the instantiated objects are set to nothing.
An error is thrown when the other forms using the object are opened.
So basically, the VBA editor action has set the objects to nothing. I have added instrumenting code to confirm this.
Has anyone seen the behavior? Does anyone have thoughts about what may be happening and causing this?
Thanks in advance...
Additional information:
The code instantiating the object in the Form_Load method is:
Set musrInfo = New usrInfo
Where usrInfo is a class module containing user information.
Also, there is no problem with earlier versions of this - I have never experienced the described problem with any other MSA VBA application. The compiled version of this particular MSA file is a bit bigger than 20MB, with little in the way of data tables - only a few parameters, etc. - and more than 13MB in forms, reports, etc.
I hope this helps... Lindsay
And there's more...
- I tried this .accdb file on another PC with Win7/MSA2010 and this
behavior did not occur.
- I then tried it in a different folder on the original PC and it
did not occur.
Maybe these findings will allow a path forward, but I still wonder why this would ever happen - why would the folder choice make any difference?

This is usual behavior.
When making changes using the VBA editor, it may recompile the VB project behind your database. This can be the whole project, or parts of it, depending on the exact change.
Recompiles will clear any variables.
You can change this behaviour, by going to Tools -> Options, under the General tab. See the following screenshot.
However, even with Compile On Demand off, you will have to trigger a recompile for most changes, clearing any set variables.
For classes that need a single instance to be publicly available as long as the database is open, I recommend setting the VB_PredeclaredID to true. That will instantiate the object as soon as the database opens, or the code recompiles. See here how.

Related

Excel VBA project crashing after compiling

I have a large userform in a project that is causing some issues when it is loaded into memory. There isn't anything exotic happening in the Userform_Initialize event (just populating combo boxes and setting default properties).
Everything was working just fine a few weeks ago when the userform wasn't as big (measured in KB). Initially, I thought the workbook was corrupted and proceeded to export every userform, module and class, re-import into a new workbook, and subsequently compiling the project as I've always done. This did not fix the issue. Interestingly enough, when I put a Stop at the top of the initialize event, and step through the code, everything works fine.
Main Idea
This got me thinking that the possible cause of the issue is the fact that the userform is very large, thus the process of loading the userform into memory is taking longer than the typical load. Essentially, the vb editor is continuing to execute the code in the initialize event, attempting to access controls that may not be in memory yet.
I have done some crude analysis to get a pretty good idea of just how large the userform in question is. The userform was exported and re-imported into a blank workbook. The workbook without the userform was around 30 KB, and with the userform, the workbook was over 350 KB, so we can conclude that the userform is around 320 KB.
It is important to note that I have extensive error handling in my project, however, I'm unable to identify this particular error as it is occurring in the initialize event (Error handling is impossible inside this particular event [Bovey, Professional Excel Development, pg 489]).
Question : With the exception of a time delay (e.g. Application.Wait or Sleep via Windows API), is there another approach to avoid crashing?
UPDATE
It turns out that delaying the application didn't work reliably either. I have actually removed the entire Initialize event to no avail as well. One thing that I forgot to mention in my original post, was that I was abusing the Debug -->> Compile VBA Project feature. See my answer below.
After dealing with this for quite some time, a colleague of mine simply commented one random line of code (not in the UserForm_Initialize, just in some random module), saved the file, and reopened it with no issues. We then discovered that the issue was not in the code, but rather with Debug -->> Compile VBA Project. For the most part, I use Debug -->> Compile VBA Project, about once every hour as I'm coding. I then save that file and continue developing on that very same compiled file. When it is all said and done, I probably run Debug -->> Compile VBA Project about 100 times over the course of two weeks. I then found this comment from Chip Pearson on this website:
VBA code is never stored as the plain text that you type in to the
editor. Input is immediately converted to platform- and
version-independent byte codes called OpCodes. These OpCodes are
converted by the editor to the text you see on the screen. When you
compile the project, the compiler translates these OpCodes to
platform- and version-specific codes called ExCodes. When you run the
code, the runtime reads the ExCodes and executes actual machine code
on behalf of the project based on the ExCodes. This whole process is
similar in principle to how Java and the Java Virtual Machine work.
If you were to export all your VBA code to text files and then remove
all the modules and then re-import the code from the text files back
into VBA (which is exactly what Rob Bovey's Code Cleaner does), you'll
see a decrease in file size. This is because the ExCodes were purged
and have not yet been recreated. Then, if you compile the project, the
file size will increase because now it stores the ExCodes in addition
to the OpCodes.
You really never need to compile the code. VBA will automatically do
it when necessary. However, the Compile command also does syntax
checking, which is its only real practical purpose.
And this is from Rob Bovey himself found here (You will also find Rob Bovey's Code Cleaner at that website):
During the process of creating VBA programs a lot of junk code builds up in your files. If you don't clean your files periodically you will begin to experience strange problems caused by this extra baggage. Cleaning a project involves exporting the contents of all its VBComponents to text files, deleting the components and then importing the components back from the text files.
I then did just as I did above in the original question. I exported all modules, re-imported them into a fresh excel workbook, added the relevant libraries, and DID NOT (as I was before) run Debug -->> Compile VBA Project. I haven't had any issues since.

Can't eliminate Access corruption

My firm's Access database has been having some serious problems recently. The errors we're getting seem like they indicate corruption -- here are the most common:
Error accessing file. Network connection may have been lost.
There was an error compiling this function.
No error, Access just crashes completely.
I've noticed that these errors only happen with a compiled database. If I decompile it, it works fine. If I take an uncompiled database and compile it, it works fine -- until the next time I try to open it. It appears that compiling the database into a .ACCDE file solves the problem, which is what I've been doing, but one person has reported that the issue returned for her, which has me very nervous.
I've tried exporting all of the objects in the database to text, starting with a brand new database, and importing them all again, but that doesn't solve the problem. Once I import all of the objects into the clean database, the problem comes back.
One last point that seems be related, but I don't understand how. The problem started right around the time that I added some class modules to the database. These class modules use the VBA Implements keyword, in an effort to clean up my code by introducing some polymorphism. I don't know why this would cause the problem, but the timing seems to indicate a relationship.
I've been searching for an explanation, but haven't found one yet. Does anyone have any suggestions?
EDIT: The database includes a few references in addition to the standard ones:
Microsoft ActiveX Data Objects 2.8
Microsoft Office 12.0
Microsoft Scripting Runtime
Microsoft VBScript Regular Expressions 5.5
Some of the things I do and use when debugging Access:
Test my app in a number of VM. You can use HyperV on Win8, VMWare or VirtualBox to set up various controlled test environments, like testing on WinXP, Win7, Win8, 32bit or 64 bits, just anything that matches the range of OS and bitness of your users.
I use vbWatchDog, a clever utility that only adds a few classes to your application (no external dependency) and allows you to trap errors at high level, and show you exactly where they happen. This is invaluable to catch and record strange errors, especially in the field.
If the issue appears isolated to one or a few users only, I would try to find out what is special about their config. If nothing seems out of place, I would completely unsintall all Office component and re-install it after scrubbing the registry for dangling keys and removing all traces of folders from the old install.
If your users do not need a complete version of Access, just use the free Access Runtime on their machine.
Make sure that you are using consistent versions of Access throughout: if you are using Access 2007, make sure your dev machine is also using that version and that all other users are also only using that version and that no components from Access 2010/2013 are present.
Try to ascertain if the crash is always happening around the same user-actions. I use a simple log file that I write to when a debugging flag is set. The log file is a simple text file that I open/write to/close everytime I log something (I don't keep it open to make sure the data is flushed to the file, otherwise when Access crashes, you may only have old data in the log file as the new one may still be in the buffer). Things I log are, for instance, sensitive function entry/exit, SQL queries that I execute from code, form open/close, etc.
As a generality, make sure your app compiles without issue (I mean when doing Debug > Compile from the IDE). Any issue at this stage must be solved.
Make absolutely sure you close all open recordsets, preferrably followed by setting their variables to Nothing. VBA is not as sensitive as it used to be about dangling references, but I found it good practice, especially when you cannot be absolutely sure that these references will be freed (especially when doing stuff at Module-level or Class-level for instance, where the scope may be longer-lived than expected).
Similarly, make sure you properly destroy any COM object you create in your classes (and subs/functions. The Class_Terminate destructor must explicitly clean up all. This is also valid when closing forms if you created COM objects (you mentioned using ADOX, scripting objects and regex). In general keeping track of created objects is paramount: make sure you explicitly free all your objects by resetting them (for instance using RemoveAll on a dictionary, then assigning their reference to Nothing.
Do not over-use On Error Resume or On Error Goto. I almost never use these except when absolutely necessary to recover from otherwise undetectable errors. Using these error trapping constructs can hide a lot of errors that would otherwise show you that something is wrong with your code. I prefer to program defensively than having to handle exceptions.
For testing, disable your error trapping to see if it isn't hiding the cause of your crashes.
Make sure that the front-end is local to the user machine, You mention they get their individual front-end from the network but I'm not sure if they run it from there or if it it copied on their local machine. At any rate, it should be local not on a remote folder.
You mention using SQL Server as a backend. Try to trace all the queries being executed. It's possible that the issue comes from communication with SQL Server, a corrupt driver, a security issue that prevents some queries from being run, a query returning unexpected data, etc. Watch the log files and event log on the server closely for strange errors, especially if they involve security.
Speaking of event log, look for the trace of the crash in the event log of your users. There may be information there, however cryptic.
If you use custom ribbon actions, make sure thy are not causing issues. I had strange problems over time with the ribbon. Log all all function calls made by the ribbon.

Loading (and executing) a lisp-file in autocad using .NET

I'm currently in the process of rewriting some old AutoCAD plugins from VBA to VB.NET. As it turns out, a (rather large) part of said plugin is implemented in LISP, and I've been told to leave that be. So the problem became running LISP-code in AutoCAD from .NET. Now, there are a few resources online who explain the process necessary to do so (like this one), but all of them takes for granted that the lisp-files/functions are already loaded. The VBA-function I'm currently scratching my head trying to figure out how to convert does a "(LOAD ""<file>"")", and the script is built in such a way that it auto-executes on load (it's a simple script, doesn't register functions, just runs from start to end and does it's thing).
So my question is. How can I load (and thus execute) a lisp-file in autocad from a .NET plugin?
Ok, there are two ways to sendcommand via .NET.
The first thing you need to understand is that ThisDocument doesn't exist in .NET.
ThisDocument is the document where the VBA code is written, but since your addin is document undependant, it stands alone and you must take the documents from the Application object.
You access the application with:
Autodesk.AutoCAD.ApplicationServices.Application
If you want to transform it to the same Application object as in VBA, with same methods and functions
using Autodesk.Autocad.Interop;
using Autodesk.Autocad.Interop.Common;
AcadApplication App = (AcadApplication)Autodesk.AutoCAD.ApplicationServices.Application.AcadApplication;
The first application has MdiActiveDocument, from where you can call the Editor and send written commands, or call the SendStringToExecute as said in other answer.
The AcadApplication has ActiveDocument (an AcadDocument object that behaves exactly as in VBA).
This document will have the same SendCommand your VBA has, use it the same way it's done in VBA.
If you can explain better the autoexecute part, I can help with that too.

MS Access closing on command button click

I have been writing VBA code for a split database, and as of late, some of the command buttons will close the instance of access on the end users machine. No warnings, no ability to stop it from happening. If I add a breakpoint, the code doesnt even hit the click event, it just closes out entirely. This however, is briefly solved by adding a NEW command button and then transferring the code over. What gives?
Repairing and compacting a database rarely seems to solve database corruption problems, and neither does decompiling it (although these can work).
I'd follow these steps (as per Dan's suggestion):
create a new database
import all objects (tables, queries, forms, reports, macros and modules) from old database
At this point it may hang on one particular form or report. If this happens, just omit this form/report from the import (although you may well be unable ever to get at it again!).
Finally, compile any VBA code, repair any references to other VBA object libraries, redraw your relationships window so it looks as pretty as it did before (the relationships themselves aren't lost; just the way they're arranged) - and curse Access!

"File not found" at the execution of any VBA code in Access 2007

I'm working on a big Access 2003 project with Microsoft Access 2007­. Recently, some users have started to experience problems with the buttons in my forms. For example, without any specific reason, clicking on a button or trying to execute any code will return the error:
File not found
There is no way to go into debug mode. When this happens the only thing to do is to restart the database. I tried adding the Stop command at the beginning of the executed block to try debugging it, but no code is executed at all. It's like a compilation error but it's only happening 5-10% of the time, which is really weird.
After some research, I found other people are having the same problem, for example this and this link. There are other examples too, with no real solutions yet.
My database can be okay for a week and then the problem starts to happen again. Half the time and users can't do much; they need to restart the database once or twice to get it back working, and after a few minutes the error might happen again.
Because this is Access 2007 and there are a lot of people experiencing this bug, I can't believe it isn't more documented.
What's the problem? Is the database somehow partially corrupted? What should I do? This is really annoying.
If I was in this situation one of the first things I would try would be to do a complete decompile+compact+recompile operation on the front-end database file, and then distribute that updated front-end out to the users to see if that improves things.
Detailed instructions on the decompile+compact+recompile steps are available here. Note: Be sure to read David W. Fenton's additional recommendations in his answer.
I had just experienced this for the first time. I had been making extensive coding changes in a form, and was required to reboot my PC without finishing debugging the code. When I opened the app, I immediately got the "file not found" message (it auto-starts a different form).
On a whim, I went to the form in question and commented out that entire module's code and the problem went away. After I went back in and uncommented that code, everything still worked as normal. I was able to continue debugging that code and lived for the rest of the day happily.
though this thread is over a year old I would like to share another very helpful observation.
This error "File not found:" may be caused by differing save behavior of Office versions and may not have anything to do with your code! In case of this error, try to open and save your troubled file in another Office version and it may work fine back in your main Office version.
Details:
Though programming VBA for years now, I had never had an unsolicited "File not found:" error. Weird also that the error message does not give a file name for the file not found. (Reminded me of another nasty error VBA sometimes shows on startup for no obious reason and erratically.) Luckily this error started after my first edits in PowerPoint 2010 after having tested the file in PowerPoint 2016. The error occurred when opening the .pptm but I had no startup procedure involving a file. So I've got the idea of some file in the .pptm zip archive not being found. Started to do a quick search on the internet and found only "shooting in the dark" suggestions. As I could start PowerPoint 2013 more easily (virtual machine) than PowerPoint 2016 (different Windows 10 boot partition), I tried to open the troubled file in PowerPoint 2013 and had no problems. I compiled the VBA project to check for error. Nothing. And save the file. After this re-saving in PowerPoint 2013, the file seems to work fine again in PowerPoint 2010 und did not show any problems after the first few edits, saves and re-opening. This being said, I wonder if PowerPoint 2016 saving is peculiar and if I can replicate/if I will run into the error again if saving the file again in PowerPoint 2016 and returning to PowerPoint 2010. (I'll make a note of this thread to add new insights once I worked with this file again in PowerPoint 2016.)
Hope this observation may spare many unnecessary un-/re-installations of Office and other desperate attempts.
Cheers!
A similar thing has just happened to me a couple of times with one of my .mdb front ends running in Access 2013, after the August 2019 update to Windows 10.
My DBs too have been through several versions of Access. On opening the database it says 'File Not Found' and throws up a public module (not one on which I have been working extensively recently), without opening the Autoexec (Switchboard) form. 'Debug, Compile' is possible and doesn't suggest any problem.
For me too, typing one space (or blank line or other character) anywhere in the code, and then deleting it, and saving, closing and re-opening seemed to provide a workaround, and all has been well for the last few days (I am the only user at present).
There is no one obvious module involved, although I will probably suspect the form module I have been working on most recently if the problem persists in a troublesome way.
Now, a few days later I have de-compiled, compacted and re-compiled the database, halving its size, so maybe that will have done the trick. I hope so.
I just had this problem. In my case, I think the issue is having a blank VBA module. I was moving procedures from one module to another and ended-up with a blank module. I couldn't delete the module manually and every time I tried to create a procedure to delete blank modules, I received the "File not found" error and the procedure I had just created was blanked out. I ended-up reverting to a backup.
The issue is just your references. One of the files for your references has been moved/deleted/updated. Remove and re-add your references to figure out which one.
I had a problem similar to this. A blank "File Not Found" error.
I turned off AutoCorrect and after clicking through several prompts/warnings which had me concerned, I then reopened the database and the error went away.
When reopening the database the problem was resolved.
I suspect this will fix many "File not found" errors which are probably related to the temporary link table losing a reference for whatever reason.
I had this same issue MS Excel.
On the user pressing a button a useless File Not Found error appeared.
I ran through all suggested above and no change or help.
COMPLETELY ACCIDENTALLY I removed a module that i use for updating the Application status. This also has some array storage within. However, on removing this module (and commenting out references to it within my code) it appears that the issue is now fixed across users.
One Issue, is I have the same Module name within several different deployment's of Excel Add-ins. I suspect that on first run Excel isn't able to automatically assume the difference between them.
I had noticed a WORK AROUND for the error in which you create a break point on the first line of code for the button in question and then resume on break - I assume that this helped Excel evaluate and namespace the modules as to not cause conflicts.
I had that problem and solved it this way: I eliminated the form where the vba code was and imported the same form from a backup file made before.
I found yet another solution (at least in my case): In trying to find the error, I tested the application I created on a co-workers computer. This somehow reset whatever went haywire in the file. Afterwards I was able to open up the file on my computer again and everything worked as it should!
EDIT: I have realized that the error, im my case, seems to have been connected in some way to my using SendKeys (see my attempt to automate a report here on SO).
Had the same problem. I stumbled on the fix by accident. For whatever reason, simply adding an on-click Event Procedure made everything better.
Open the form in design mode
Select an object on the form
Press F4 to display the object's properties
Event > On Click > dropdown > click [Event Procedure]
Then click the three dots, which will create a new event, and launch the Visual Basic editor. This will also add default code into the Visual Basic editor
Make no other changes
Save and close changes to the form
Restart the database
For what its worth, as I was wrestling with this issue, the error resolved itself in other ways, but none of them were repeatable.
I had this problem as well, and compact/repair did not fix it. In my case I had an old VBA module that was no longer used, and which referenced an object class that no longer existed. Removing the non-compiling code fixed the issue for me.
I have had this problem for many years now in access 2010. Always in the Autoexec form that opens on msaccess startup. I tried creating a very simple form that calls the original more complex form. To my surprise the more problem moved the the new simple form. By trial and error, I found that just editing the new simple Autoexec form the problem would go away, but turn up randomly months later ALWAYS after I had made programming changes elsewhere. Sometimes instead of the file not found error, I get just get a crash out of access - but the solution is the same procedure - make a small edit to the autoexec file (just add new blank line will do). My project has come through many versions of access (2000 -> 2010). If there was some way to automate the editing of my autoexec form, then restarting access - this would serve as a workaround. I have not found any way as yet.
I have had this problem for years in my access database. I tried all the above solutions an they all fixed the problem, only to have the problem reappear sometime later - always after VBA code change. I discovered that decompiling and then recompiling ALWAYS FIXES this problem, and is the quickest and easiest way to do so. So I have concluded that there is a bug in way Office only partly compiles after program changes like macros and VBA code changes. After a number of changes the system gets 'unhinged' and throws up the 'file not found' error. Reading thru the fixes users have found in this blog supports my theory. Nearly all these fixes would probably cause some sort and recompile the unhinged code.
MY SOLUTION
In summary I have found the following..
Doing a Decompile (without a recompile) will get rid of the error - but if the code is run on a different machine the error appears again.
Doing a decompile, then a recompile followed by a Compact and Repair results makes my app run on other machines with out any problems.
I had a class module - Class1 - that was not used. I deleted it and did a compact and repair.
Something happened that caused the name of the class module to stay in the Navigation Pane but the module as such was removed:
When opening the VBA editor I got the "File not found".
Impossible to delete the name from the Navigation Pane!!
When decompiling the project I got "An error occurred while loading 'Class1'. Do you want to continue loading the project?"
I did - now the Class1 was still in Navigation Pane when opening project again but now I could delete from the Navigation Pane.
After that the message about file not found no longer appeared.
FYI