I am seeking comments on how to schedule auto updates of a database (.accdb) since I am not very comfortable with the process I have set up.
Currently, it works as follow:
Task Scheduler calls a .bat
.bat calls a .vbs
.vbs opens the database and calls a macro
The macro calls a function (VBA Level)
The function calls the update Subroutine
I consider there are too many steps and the fact that it requires 2 external files (.Bat and .vbs) related to the database and stored on the system increase the risk that the procedure would break.
Apparently (but please tell me that I am wrong and how I can change it) .vbs cannot call a subroutine but only a macro. Identically, an access macro cannot call a subroutine but only a function if the user is expecting to enter the VB environment of the database. This is the reason why I called a function (VBA Level) that then calls the subroutine.
Hope some of you know how to shorten the steps and eventually get ride of the .bat and .vbs
To the best of my knowledge the shortest path for a Windows Scheduled Task to "do something useful in Access VBA" is:
Create a Public Function (not Sub) in the database. For example:
Option Compare Database
Option Explicit
Public Function WriteToTable1()
Dim cdb As DAO.Database
Set cdb = CurrentDb
cdb.Execute "INSERT INTO Table1 (textCol) VALUES ('sched test')", dbFailOnError
Set cdb = Nothing
Application.Quit
End Function
Create a Macro in the database to invoke the function:
Create a Windows Scheduled Task to invoke MSACCESS.EXE with the appropriate parameters
In the above dialog box the values are:
Program/script:
"C:\Program Files\Microsoft Office\Office14\MSACCESS.EXE"
Add arguments (optional):
C:\Users\Public\schedTest.accdb /x DoSomething
A VBS script can call any standard VBA SUBROUTINE with the following:
dim accessApp
set accessApp = createObject("Access.Application")
accessApp.OpenCurrentDataBase("C:\MyApp\MultiSelect.mdb")
accessApp.Run "TimeUpDate"
accessApp.Quit
set accessApp = nothing
Note that the sub TimeUpDate is a standard VBA subroutine. This means no Autoexec macros, and no macros at all - only pure VBA sub calls + this VBS script.
There is a little known trick dating back to the earliest years of access to allow it to run as a process which still works. Access will always on startup look for a macro called "Autoexec". If it finds it it will immediately start executing this macro. I find this is extremely useful if I need to initialise the program before opening forms or, as in the case of the original questioner, run access as a scheduled process with no user I/O.
After beating my head against the wall for about four hours, I finally got this to work:
1) Create a DOS batch file with one line it. The line is composed of three parts a) the full path to Microsoft Access (msaccess.exe), b) the full path of the Microsoft Access database with the code in it, and c) the Access command line argument "/x MacroName". The first two items should be surrounded with quotes. Mine looks like this:
"C:\Program Files (x86)\Microsoft Office\Office14\MSACCESS.EXE" "C:\MyPrograms\ProdDB Reports\ProdDB Reports.accdb" /X DailyTestReportsRun
2) Create a macro inside of Access with the name you used in your batch file. It has one command, RunCode, with an argument of the name of a VBA function you want to call. This should be followed by open/close parenthesis "()". I didn't try passing any parameters to the function; I think this would be problematic.
4) Make sure the VBA function you call has a Docmd.Quit command at the end, or that you add this as a second line to your macro. These will make sure that Access doesn't stay open after your process runs.
5) In Windows Task Scheduler, select "create a basic task" (which invokes a wizard). Set the program name to the name of your DOS batch file. There's a helpful check box labeled something like "Open the properties window when I'm finished." Check that so you that go to the properties window.
6) Set the task to run regardless of whether the user is logged on or not. Also check on the "Run with highest privileges" box, which one friend on here suggested.
You can now test everything by right-clicking the scheduled task and selecting the Run command.
I liked Albert Kallal's script and tried it. Everything worked great until I tried to schedule it. Then, for some mysterious reason the scheduler would not kick it off.
none of the above work
ms access DB with task scheduler will not work as to open the db run code and quit the application
the solution I found is to avoid task scheduler and have the ms access db open all time and have a timer in msaccess do the job
Related
I'm trying to make the MS Access command-line parameter /x work. How do I FULLY specify in the command line the macro's location IN the Access database? I'm NOT trying to do an AUTOEXEC setup.
The database opens but keeps giving me "macro not found" errors. I've tried variations after the /x command, including things that match "examples" on the Web but none work. I've tried it as both a Sub and a Function.
I also tried setting up a RunCode macro named Show_Msg and I get the same "can't find" error message with that. I tried the full path with both periods and bangs and neither worked.
I'm pretty much sure the problem is that I need to specify the FULL path WITHIN Access, i.e., Project, Module, Sub/Function.
Windows Command line:
"F:\CLIENT DOWNLOADS\TDN\TXE_DEN.accdb" /x z_show_msgbox
Trying to run:
Function z_show_msgbox() _
As Variant
' denImport.z_show_msgbox
MsgBox "JUST TO SEE HOW TO RUN A SUB" _
& "DIRECTLY FROM WINDOWS"
z_show_msgbox = True
End Function
Project: TXE_DEN
Module: denImport
I expect the specified database to open (which it does) and run the sub or function or macro.
When /x has the sub/function name the error message is:
Microsoft Access cannot find the object 'z_show_msgbox.' If
'z_show_msgbox' is a new macro or macro group, make sure you have
saved it and that you have typed its name correctly.
I get a similar error when /x has the macro name instead of the function.
Thanks! I had tried the macro approach too but that didn't work either.
The problem was that I had the macro code set up as:
Function: z_show_msg
(no following parentheses)
When I changed that to
Function: z_show_msg()
it now works.
I had created the macro but didn't test it because it's only one command and I knew the function worked.
With the macro properly set up this works:
"F:\CLIENT DOWNLOADS\TDN\TXE_DEN.accdb" /x Show_Msg
I would like to know if there is an easy workaround for my following question. I have an access database that have different modules in vba (and of course each module with different subroutines). How can I do to create an icon or an executable file that by clicking on it it runs one of the subroutines of one of the modules without opening access?
The reason of this is because when I am away people need to run some of these subroutines and these users don't have any experience with Access.
You can start Access with a command line option to run a named Access macro. (That means an Access macro object. Some people also call VBA procedures macros, but an Access macro object is different.)
An Access macro has a RunCode method which you can use to run a VBA function. Since the code you want to run is a subroutine, create a new function which calls that subroutine and shuts down Access afterward, and use the function with the macro's RunCode method.
After you have the macro working correctly, test it from a Windows Command Prompt session following this pattern:
"<path to MSACCESS.EXE>" "<path to db file>" -X <macro name>
After working out those details, you can create a desktop shortcut to do the same thing.
However, if your Access operation must be run by you or another user on a regularly scheduled basis (daily, weekdays only, etc.), you could create a Windows Scheduled Task to do it and forget about other users and desktop shortcuts.
Note this suggestion isn't exactly what you requested because it does open Access. But it could close Access after the operation is finished, so perhaps it will be acceptable.
I'm running a scheduled task in Windows Server 2003. When the scheduled task runs, it calls a VBA Macro which runs, does some database stuff, then exits.
The VBA Macro needs to return a non-zero value to the Shell / Scheduled Task Manager if something goes wrong in the Macro (for instance a database goes down).
Is it possible to return a non-zero value from the vba macro to notify the Scheduled Task Manager that something has gone wrong? I'd like to be able to fish the value out of SchedLgU.txt so I can be notified when something goes wrong.
If you're willing to use an API call it can:
Private Declare Sub ExitProcess Lib "kernel32" (ByVal uExitCode As Long)
In your code, you can exit with a value, like 7, for the example below:
Call ExitProcess(7)
Note that calling the above will immediately exit Access without any prompt or saving or anything. It should be the very last thing you do.
Tested on Access 2003 Pro (build 11.8321.8324) SP3.
Steps to reproduce:
create a new database.
create a new form.
put a button on the form.
paste the following code in the button's Click event procedure:
Debug.Print Workspaces.Count
Debug.Print CurrentDb.Name
close the code editor and form, saving changes.
do not skip this step: close Access.
re-open Access and your database.
open the form
click the button
click the toolbar button to switch the form to design mode.
You should see the following error dialog:
You do not have exclusive access to the database at this time. If you proceed to make changes, you may not be able to save them later.
Does anyone know what is going on here?
The simple workaround is to call CurrentDb prior to calling Workspaces for the first time:
Debug.Print CurrentDb.Name
Debug.Print Workspaces.Count
Debug.Print CurrentDb.Name
I'll take a shot at demystifying what's going on, but this is just my theory.
The relevant bits of the Access help file are as follows (for CurrentDb):
Note In previous versions of
Microsoft Access, you may have used
the syntax
DBEngine.Workspaces(0).Databases(0) or
DBEngine(0)(0) to return a pointer to
the current database. In Microsoft
Access 2000, you should use the
CurrentDb method instead. The
CurrentDb method creates another
instance of the current database,
while the DBEngine(0)(0) syntax refers
to the open copy of the current
database. The CurrentDb method enables
you to create more than one variable
of type Database that refers to the
current database. Microsoft Access
still supports the DBEngine(0)(0)
syntax, but you should consider making
this modification to your code in
order to avoid possible conflicts in a
multiuser database.
And for the Workspaces collection:
When you first refer to or use a
Workspace object, you automatically
create the default workspace,
DBEngine.Workspaces(0).
It would seem that by creating the default workspace prior to the first call to CurrentDb, you are somehow causing CurrentDb to forget how it should work. It seems that instead of creating a new instance of the current database it just uses the one that's already lying around in the default Workspace.
Of course, this is all conjecture and I'm as curious as you to know the "real answer".
I'm trying to open a series of Excel spreadsheets using an instance of Excel created inside of a module in an Access database. I can get the files to open properly; however, the actual call to make Excel start takes quite a while, and to open the files takes even longer. The location of the files doesn't matter (same time to open on a local HDD as a network drive).
In an attempt to figure out what was taking so long, I added a timer to the logging module. Opening the files takes approximately 2m30s, during which the host application (Access) is entirely unresponsive to user input); the rest of the script executes in less than 10 seconds.
I'm using the standard Excel.Workbooks.Open call as follows
Set OpenSpreadsheet = Excel.Workbooks.Open(Name, 2, False)
Using Debug.Print methods around this line says it can take up to 2 1/2 minutes for this one line to execute.
Is there anything I can do to make the Excel files open quicker?
EDIT: When opening, UpdateLinks is False and ReadOnly is True; all other options are left to their defaults.
First idea: Can you use a jet driver with an ODBC connection to Excel, instead of opening it in an Excel object? Might be much faster.
Second idea: Make sure to create and instantiate the Excel application object just once at the beginning of the routine, then use the Excel.Workbooks.Open() and Excel.ActiveWorkbook.Close() for each spreadsheet. That way you're not "re-launching" the MS Excel application each time.
To draw out the second of #BradC's well-advised recommendations, if you need to use Excel in more than one procedure, create a self-initializing global function. I always use late binding for automating Office apps.
Public Function Excel(Optional bolCleanup As Boolean = False) As Object
Static objExcel As Object
If bolCleanup Then
If Not objExcel Is Nothing Then
Set objExcel = Nothing
Exit Function
End If
End If
If objExcel Is Nothing Then
Set objExcel = CreateObject("Excel.Application")
End If
Set Excel = objExcel
End Function
Then you can use it in code without needing to initialize it, and the single instance will remain available to any code that needs to use Excel.
And when you shut down your app, you'd call Excel(True) to clean up.
I do this with Outlook and Word all the time. However, there are some COM apps that it works poorly with, such as PDF Creator, which doesn't take kindly to this kind of treatment (you end up in an endless loop with it shutting down and re-initializing itself if you try to destroy the instance this way).
Another approach depends on your setup and process.
In my case I need read-only access to a set of Excel documents stored on SharePoint. My code is currently like:
For each path in paths
set wb = Workbooks.open(path,false)
next
In this case, each workbook is individually downloaded each time a workbook is opened. It would be significantly more efficient if the files were downloaded asyncronously and after the download is complete, the rest of the process executes on the local disk.
My idea is to use CopyFileEx() and pass a callback function. Excel will then download the Excel documents to disk asynchronously and call a VBA function regarding progress. When all files are completed, we can launch the next part of the process, which opens the local workbooks, scans them and then removes them from the local drive.
I'll post code later if I manage to implement it.