Multiple instances of same access database are open on 1 machine - problem - vba

I'm having issues with a ms access 2007 accdb, using Windows Server 2008 task scheduler for scheduled tasks. The problem is the file that's being opened by the task scheduler is opening/closing properly, but the 'lock' file (.laccdb) remains visible after the database is closed, which is an indicator that the access db thinks it's still open. Each time a new task runs, a new instance of access is being opened. I opened the Schema to show roster of all users in the database and it's showing 3 duplicates of the server name/Admin account. Below is an example of the immediate window in access:
COMPUTER_NAME LOGIN_NAME CONNECTED SUSPECT_STATE
SERVER Admin True Null
SERVER Admin True Null
SERVER Admin True Null
I'm hoping someone else has had this problem and knows 1) How to easily close all the open instances of access and 2) how to prevent this from occuring when running a task. I have "Do not start a new instance" set under the task's 'settings' tab, but this is irrelevant b/c none of the tasks were running simultaneously. Thanks in advance for any assistance.

To close all open Access instances (you can't run this from Access because you can't guarantee that the running instance will be the last reference you retrieve):
Sub CloseAllAccessInstances()
Dim acc As Access.Application
Do
Set acc = GetObject(, "Access.Application")
If IsNull(acc) Then Exit Do
acc.Quit
Loop
End Sub
After you run the above, check the task manager. If you see msaccess.exe, then you most likely have a circular object reference. This will prevent Access from closing. For more information, have a look at http://msdn.microsoft.com/en-us/library/aa716190(VS.60).aspx.

Related

calling a uid and pwd file into an access db for a system dsn

I have 5 different MS Access 2013 db files which connect to system dsn files(Linked Server)
The machine/system dsn's are Oracle based but the issue I am running into is 1 my password isn't encryped and has to be changed every 90 days and
2 I have to open each file and save my password multiple times when its changed.
I want to have a secure location which has the credentials stored and pass this into access so that they are not visible to other users and
not having to save my password on each access file and relink it.
I have googled for over 2 days but can't find anything other than looking at connection strings which still doesn't solve the problem. What do I need to look at to solve this?
Sorry I dont have code as I just use the linked tables wizard inside of ms access.
#Albert D I couldn't get your code to work but I have done the following which fixes the issue on the tables but not the Pass Through queries
Created a File DSN and linked some tables to the access database.
Created an Excel File to store my UserName And Passwords but my credentials in the pass-through query still show which I am stuck on?
Option Compare Database
Function Connections()
On Error Resume Next
'delete query if exists
DoCmd.DeleteObject acQuery, "PTQ"
Err.Clear
On Error GoTo 0 '"on error" statement here
'GET EXCEL LOGIN DETAILS
Set xlsApp = CreateObject("Excel.Application")
Dim WkBk As Excel.WorkBook
Set WkBk = xlsApp.WorkBooks.Open(FileName:="C:\folderlocation\filename.xlsx")
Dim USERLIST As String
Dim PWDLIST As String
USERLIST = WkBk.Sheets(1).Range("A2").Value
PWDLIST = WkBk.Sheets(1).Range("B2").Value
If Not (xlsApp Is Nothing) Then xlsApp.Quit
'end excel stuff
Dim db As DAO.Database
Dim qdExtData As QueryDef
Dim strSQL As String
Set db = CurrentDb
'passthrough query statement
strSQL = "SELECT * FROM table"
Set qdExtData = db.CreateQueryDef("PTQ")
ServerName = "Server1"
qdExtData.Connect = "ODBC;DRIVER={Oracle in OraClient11g_home1};Server=" & ServerName & ";DBQ=Server1;UID=" & USERLIST & ";Pwd=" & PWDLIST & ""
qdExtData.SQL = strSQL
qdExtData.Close
db.Close
Set db = Nothing
End Function
I then Set up a runcode macro called AutoExec
Ok, first up?
I would avoid (not use) a system, or a user DSN. The reasons are MANY, but these types of DSN's require not only a external reference, but also often require elevated registry rights. And worse yet, your password will be in plain view.
The best solution is to use what is called a DSN-less connection. And you can create these connections even without code!
And even better? If the server + database name is NOT changed, but ONLY the password? You can change the userID + password WITHOUT having to re-link the tables (ideal for you with a changing password, but NOT the server + database being changed).
Even better better? If you adopt a wee bit of "log on" code, then you don't have to store the password in the table links! What this means if someone decides to fire up access, and say import your linked tables? Well, for one, they will not be able to open the tables, and EVEN better yet the uid/password is NOT part of, nor is it stored in the connection string for each linked table. As noted, because of this, you can change the UID, and not have to re-link the tables.
The first step:
First up, ALWAYS (but ALWAYS!) when you link the tables, use a FILE dsn. this is imporant since when using a FILE dsn in access, they are automatic converted to DSN-less connections for you.
In other words, if you link your tables with a FILE dsn, then once the tables are re-linked, then you can even delete or toss out the DSN. And this means you can deploy the linked database (front end) to any workstation. You will not have to setup a DSN on that workstation, and in fact don't have to setup anything at all. (you will as before of course require the oracle database driver).
What the above means is when a password is updated/changed, you could then simply roll out a new front end. In fact, you likely have some auto updating ability for your application. (and if you don't', then you could (should) cobble together a bit of code to do this for you). So, you should have some means to roll out a new version of your software. After all, you REALLY have to install your "application" on each workstation LIKE you do with all other software, right???
So, there are two parts here:
Adopting a FILE dsn for the table links. As noted, once you do this, then you don't need the DSN anymore. This is great for distribution to each workstation.
Also MAKE SURE when you do link, you do NOT check the box to save the password. This is to ensure that uid/password is NOT saved in the connection strings.
So, if tables don't have uid/password, then how will they work?
Well, what you do is execute a "logon" to the database in your startup code. Once you execute this logon, then all linked tables will work! It is this "small" bit of code that can read the uid/password you place in an external file. Where you place this uid/password is up to you. It could be embedder in the code, or even some external text file that you read on startup. And it could even be a local table in the front end. (this idea would work well if you have some kind of automatic update system for when you roll out the next great version of your software.
So, with the ability to execute a logon, and not having to re-link the tables, then we have a EASY means to change the password.
So, you have to:
go dsn-less. Thankfully, access does this by default, but ONLY if you use a FILE dsn.
Get/grab the code to execute a logon to the database. In fact, you likly have to delete all your table links. Exit Access, then re-start Access. Now, run your logon code, and THEN re-link your tables (using a FILE dsn you make).
The code to execute a logon is this:
Function TestLogin(strCon As String) As Boolean
On Error GoTo TestError
Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef
Set dbs = CurrentDb()
Set qdf = dbs.CreateQueryDef("")
qdf.connect = strCon
qdf.ReturnsRecords = False
'Any VALID SQL statement that runs on server will work below.
qdf.sql = "SELECT 1 "
qdf.Execute
TestLogin = True
Exit Function
TestError:
TestLogin = False
Exit Function
End Function
The above of course requires a correctly formed conneciton string.
So, to make ALL of this work, you can adopt the FILE dsn, and use above. You will likly cobbile together some code to build you a connection string. Then add to your code some code to read an external ext file, or have the UID/password in some table. This logon code as per above has to run BEFORE any form or linked table is used or touched.
The whole process is simple, but only if you break down this into the correct steps.
How this logon trick, and example code works is not complex, but a full article explaining this approach is outlined here
Power Tip: Improve the security of database connections
https://www.microsoft.com/en-us/microsoft-365/blog/2011/04/08/power-tip-improve-the-security-of-database-connections/

Open Access database while holding shift key using .vbs

So I am looking to open an access database on a daily basis using task scheduler. I want this script to open the .aacdb and then open a specific form. The problem is, this database has an auto executable that opens a different form that will close the program when exiting out of it. I need to somehow bypass this executable. I've been trying to write a .vbs script that will use the hold down shift key (to bypass the auto executable) > open database > release shift key > open form > close database. After days of searching, I can't seem to find any answers on whether this is possible. Here is what I have so far (it opens the database but doesn't bypass the auto executable). The aim of this script is to hold down the shift key for 10 seconds while opening the database.
b = DateAdd("s", 10, Time)
Set WshShell = CreateObject("WScript.Shell")
Set appAccess = CreateObject("Access.Application")
appAccess.Visible = True
strDBNameAndPath = "C:\FileFolder\file.aacdb"
Do While (Time < b)
WshShell.SendKeys "+"
Loop
appAccess.OpenCurrentDatabase strDBNameAndPath
Set WshShell = Nothing
I can't mess with the actual database (the macros), this has to happen by somehow bypassing the actual auto executable upon opening a database. Is this possible in .vbs? .vba? .vb? vb.net? any language?? I'm only familiar with .vbs. But any insight would be helpful. Thanks!!!

Preventing Scheduled Agent from executing when modified

I have a scheduled agent that runs Weekly at one particular time on a target of All new & modified documents.
If I modify this agent, even if I only save it, it runs again.
If I remember correctly from long long ago, I have to add code such as this:
Dim db As NotesDatabase
Dim agent As NotesAgent
Set db = s.CurrentDatabase
Set agent = db.GetAgent("myAgent")
If agent.HasRunSinceModified = False
Exit Sub
End If
Am I remembering correctly? And I always wondered, why would an agent fire off after being modified? Makes no sense to me.
My response corresponds to your title: Preventing Scheduled Agent from executing when modified.
The solution is to move all your code to a script library, and never change the agent (since no need of it).
When you modify your code in the script library the agent is not fired.
You can also read Notes Designer runs agent after saving which suggest (I didn't test) Amgr_SkipPriorDailyScheduledRuns=1

SSIS Excel RefreshAll() task SQL job fails when no one logged in

A few months ago, I made a SSIS package that is used to refresh a couple excel worksheets (+few other things)
Now, my college that is still on the project reports this weird behavior.
The SSIS package is scheduled as SQL Agent Job.
It runs hourly from 8am00. At 8am it always fails, his conclusion: at 8am is no one logged on the server.
The second time, at 9am, the job runs OK. (RefreshAll worked) His conclusion: there is always someone logged on the the server via RDP at that moment.
(In fact I don't know about the other runs later on the day)
The task is a VB Script task that calls the Excel Interop dlls. I remember having difficulties to get it working until I installed Excel 2010 x86 on the server. -> Excel is fully and legitimately installed on the server.
My guess and determination at that moment was that it sometimes went wrong somewhere and Excel did not close properly. When I opened taskmgr I found +10 instances of Excel.exe running... This was during development.
My college did an interesting test: scheduled the job every minute and logged on and off a few times to the server. Every time no one was logged on to the server (RDP) the job failed. When logged on, the job ran OK !
Below the code that is used in the 'RefreshAll' script task.
I also used threading.sleep because otherwise I got timeout errors. Found no other way.
Thanks in advance!!
L
Public Sub Main()
Dts.TaskResult = ScriptResults.Success
Dim oApp As New Microsoft.Office.Interop.Excel.Application
oApp.Visible = False
'oApp.UserControl = True
Dim oldCI As System.Globalization.CultureInfo = _
System.Threading.Thread.CurrentThread.CurrentCulture
System.Threading.Thread.CurrentThread.CurrentCulture = _
New System.Globalization.CultureInfo("en-US")
Dim wb As Microsoft.Office.Interop.Excel.Workbook
wb = oApp.Workbooks.Open(Dts.Variables("User::FileNameHandleFull1").Value.ToString)
oApp.DisplayAlerts = False
wb.RefreshAll()
Threading.Thread.Sleep(10000)
wb.Save()
wb.Close()
oApp.DisplayAlerts = True
oApp.Quit()
Runtime.InteropServices.Marshal.ReleaseComObject(oApp)
End Sub
End Class
Excel is a client application and normally it does require to have active user session on a machine it runs on. For a job like this, I would consider other approaches not involving working with excel process, eiter:
store the result in a sql server table, then use linked table from excel sheet to pull the data.
use export as .csv (comma separated values)
use 3rd party controls that write Excel format
they may fix it in next version of Excel?

Intermittent error when attempting to control another database

I have the following code:
Dim obj As New Access.Application
obj.OpenCurrentDatabase (CurrentProject.Path & "\Working.mdb")
obj.Run "Routine"
obj.CloseCurrentDatabase
Set obj = Nothing
The problem I'm experimenting is a pop-up that tells me Access can't set the focus on the other database. As you can see from the code, I want to run a Subroutine in another mdb. Any other way to achieve this will be appreciated.
I'm working with MS Access 2003.
This is an intermittent error. As this is production code that will be run only once a month, it's extremely difficult to reproduce, and I can't give you the exact text and number at this time. It is the second month this happened.
I suspect this may occur when someone is working with this or the other database.
The dataflow is to update all 'projects' once a month in one database and then make this information available in the other database.
Maybe, it's because of the first line in the 'Routines' code:
If vbNo = MsgBox("Do you want to update?", vbYesNo, "Update") Then
Exit Function
End If
I'll make another subroutine without the MsgBox.
I've been able to reproduce this behaviour. It happens when the focus has to shift to the called database, but the user sets the focus ([ALT]+[TAB]) on the first database. The 'solution' was to educate the user.
This is an intermittent error. As this is production code that will be run only once a month, it's extremely difficult to reproduce, and I can't give you the exact text and number at this time. It is the second month this happened.
I suspect this may occur when someone is working with this or the other database.
The dataflow is to update all 'projects' once a month in one database and then make this information available in the other database.
Maybe, it's because of the first line in the 'Routines' code:
If vbNo = MsgBox("Do you want to update?", vbYesNo, "Update") Then
Exit Function
End If
I'll make another subroutine without the MsgBox.
I've tried this in our development database and it works. This doesn't mean anything as the other code also workes fine in development.
I guess this error message is linked to the state of one of your databases. You are using here Jet connections and Access objects, and you might not be able, for multiple reasons (multi-user environment, unability to delete LDB Lock file, etc), to properly close your active database and open another one. So, according to me, the solution is to forget the Jet engine and to use another connexion to update the data in the "other" database.
When you say "The dataflow is to update all 'projects' once a month in one database and then make this information available in the other database", I assume that the role of your "Routine" is to update some data, either via SQL instructions or equivalent recordset updates.
Why don't you try to make the corresponding updates by opening a connexion to your other database and (1) send the corresponding SQL instructions or (2) opening recordset and making requested updates?
One idea would be for example:
Dim cn as ADODB.connexion,
qr as string,
rs as ADODB.recordset
'qr can be "Update Table_Blablabla Set ... Where ...
'rs can be "SELECT * From Table_Blablabla INNER JOIN Table_Blobloblo
set cn = New ADODB.connexion
cn.open
You can here send any SQL instruction (with command object and execute method)
or open and update any recordset linked to your other database, then
cn.close
This can also be done via an ODBC connexion (and DAO.recordsets), so you can choose your favorite objects.
If you would like another means of running the function, try the following:
Dim obj As New Access.Application
obj.OpenCurrentDatabase (CurrentProject.Path & "\Working.mdb")
obj.DoCmd.RunMacro "MyMacro"
obj.CloseCurrentDatabase
Set obj = Nothing
Where 'MyMacro' has an action of 'RunCode' with the Function name you would prefer to execute in Working.mdb
I've been able to reproduce the error in 'development'.
"This action cannot be completed because the other application is busy. Choose 'Switch To' to activate ...."
I really can't see the rest of the message, as it is blinking very fast. I guess this error is due to 'switching' between the two databases. I hope that, by educating the user, this will stop.
Philippe, your answer is, of course, correct. I'd have chosen that path if I hadn't developed the 'routine' beforehand.
"I've been able to reproduce this behaviour. It happens when the focus has to shift to the called database, but the user sets the focus ([ALT]+[TAB]) on the first database. The 'solution' was to educate the user." As it is impossible to prevent the user to switch application in Windows, I'd like to close the subject.