When using VBA on a window with ActiveX Data Object (ADO) to connect to SQL Server to read and/or write data to tables, the best practice is to open the ADO connection on the Window_BeforeOpen() event and to close the ADO connection using the Window_AfterClose() event.
This is similar to the best practice for reports discussed in the Using ADO with VBA with Report Writer post.
There is one big difference in behaviour between windows and reports that can cause problems with this technique…. cue dramatic music…..
Windows have a user interface which might cause a dialog to open and the window closure to be aborted.
OK, big deal, why should this cause a problem for us?
Well, let’s work with the following scenario:
- The user opens the window and the Window_BeforeOpen() event opens the ADO connection.
- The user is working in the window and the VBA code is reading and writing via ADO as desired.
- The user is has finished editing data in the window (but has not saved) and closes the window.
- The “Do you want to Save, Discard or Cancel?” dialog opens and the user decides to cancel.
- The window closure is aborted and the window stays open.
- The user continues working and the next time VBA attempts to use ADO, the following error shows up:
Run=time error ‘3709’:
Requested operation requires an OLE DB Session object, which is not supported by the current provider.
So what happened?
The issue here is that while the Dexterity WIN_POST script aborted the window closure, the script itself as still executed. Therefore the VBA Window_AfterClose() script also executed… and closed the ADO connection even though the window remained open.
The solution to this issue is to make sure that the Window_AfterClose() script does not close the ADO connection if Cancel was selected on the pop up dialog.
Please see the Knowledge Base (KB) Article below for details of the solution including example scripts:
- How to use ActiveX Data Object (ADO) with VBA on a window with Microsoft Dynamics GP and with Microsoft Business Solutions – Great Plains 8.0 (KB 942327)
Hope you find this one useful.