Automating access 2003 application - vba

I have an access application (VBA) ( access 2003 ) , which generates 4 different text file based on its database at specific path on pressing of 4 respective different buttons.
But this is something manual , which i do everyday for the file generation.
Im in need of its automation.For example my file should get automatically generate at any specific time.
One of the button's event procedure is menitoned below :
I tried doing with help of VB script , but this is giving error .
"Provider cannot be found.May not be properly installed "
Set objAccess = CreateObject("Access.Application")
Set conn = CreateObject("ADODB.Connection")
strConnect = "Provider=Microsoft.JETs.OLEDB.12.0;
Data Source=E:\Project\test.mdb"
conn.Open strConnect
test()
function test()
objAccess.DoCmd.Hourglass True
objAccess.DoCmd.SetWarnings False
objAccess.DoCmd.RunSQL ("INSERT INTO Table1 ( name, FileName, [DateTime] ) SELECT Environ(""UserName"") AS name, ""test.mdb Generate ABCD File"" AS FileName, Format(Now(),""yyyyMMddhhmmss"") AS [DateTime];")
objAccess.DoCmd.OpenQuery ("qry_ABCD")
objAccess.DoCmd.TransferText acExportDelim, "qry_ABCD_Formatted Export Specification", "qry_ABCD_Formatted", "E:\Ouputs\" & Format(Now(), "yyyymmdd") & ".txt", False
objAccess.DoCmd.SetWarnings True
objAccess.DoCmd.Hourglass False
End function
I dnt know how to resolve this issue. Or is there any other better way to resolve this.

There is no need to setup or create some connection string in your script. Once you opened Access, then you have use of all tables in that application. And in fact in your example you create a conneciton object, but it not really required.
So, lets assume your VBA code to run is this:
Sub MyExport()
Dim strSQL As String
strSQL = "INSERT INTO Table1 ( name, FileName, [DateTime] ) " & _
"SELECT Environ(""UserName"") AS name, ""test.mdb Generate ABCD File"" AS FileName, " & _
"Format(Now(),""yyyyMMddhhmmss"") AS [DateTime];"
CurrentDb.Execute strSQL
DoCmd.TransferText acExportDelim, "qry_ABCD_Formatted Export Specification", _
"qry_ABCD_Formatted", _
"E:\Ouputs\" & Format(Now(), "yyyymmdd") & ".txt", _
False
End Sub
The above code is assumed to be saved as a sub (not a function) in a STANDARD MS Access VBA code module.
Now, your VBS scrip can call the above code like this:
dim accessApp
set accessApp = createObject("Access.Application")
accessApp.OpenCurrentDataBase("C:\some path name\someMdb.accDB")
accessApp.Run "MyExport"
accessApp.Quit
So it now a simple matter to run the above VBS script. And such a script should also just run fine via the windows task scheduler. As above shows there is LITTLE need to put the SQL and code in the VBS script. You BEST get the sub working in VBA and MAKE SURE it works. Test it many times, and THEN and ONLY then do you create the VBS cript to call that sub. So FIRST get the routine working, and get it working WITHOTU any prompts etc. You can call and test the VBA sub by placing your cursor in the VBA editor in that routine, and then hit F5 to run the sub. Once you get it working the way you want, then you use the above second VBS (not VBA script to call + run that working sub that you are NOW 100% SURE it works and runs correctly)

Related

Running VBS script from VBA - Unrecognized DB Format

I'm creating vbs script that will work as auto updater for tool which uses MS Access as front end. VBS script will be launched with VBA code from MS Access (1). Part of this script is function that detects current version of the tool by creating ADODB connection to tool front end file (Test.accdb) and reading "CurrentVersion" value from "tblLocalParameters" table (2).
The problem is that when I double click on script the function with ADODB works correctly but when I try to run it with MS Access VBA it throws out error:
"Unrecognized database format"
I'm not sure if more information about whole auto updater script is necessary but my plan was to: Check with SQL db if tool is up to date. If not - launch updater script. Script will close MS Access with shell command then copy new file and run MS Access again.
I tried to run same script from excel and from other MS Access file, it caused same error.
I'll be gratefull for help with getting rid of "Unrecognized database format" error.
MS ACCESS CODE:
(1)
Dim Test()
Shell "wscript ""C:\Test_Folder\TEST.vbs""", vbNormalFocus
End Sub
(2)
VBS SCRIPT CODE
Option Explicit
Dim strFile
strFile = "C:\Test_Folder\TEST.accdb"
WScript.Echo FileReadAccessDB(strFile,"tblLocalParameters","ParameterValue","ParameterName","'VersionCurrent'")
'-------------------------------------------------------------
Function FileReadAccessDB(DbPath, tblName,fldName,IdCol,IdVal)
Dim cn, rs
Dim qSQL
Dim errNo
Set cn = CreateObject("ADODB.connection")
cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DbPath & ";Persist Security Info=False;"
cn.Open
Set rs = CreateObject("ADODB.recordset")
qSQL = "SELECT " & fldName & " FROM " & tblName & " WHERE " & IdCol & " = " & IdVal
rs.open qSQL, cn
FileReadAccessDB = rs.fields(fldName).value
rs.close
cn.close
End Function
I found source of the issue. I decided to abandon VBS and create C# console app. During testing I found that connection string (provider = "Microsoft.ACE.OLEDB.12.0") works only when I set platform target to x64.
My Windows is 64bit but Office is 32bit. Double click in explorer launched the scrip as x64 but MS Access vba shell launched it as x86.
I found some code, added it to the script - it solved the problem.
If InStr(LCase(WScript.FullName),"syswow64") Then
CreateObject("WScript.Shell").Run """%systemroot%\sysnative\wscript.exe"" """ & WScript.ScriptFullName & """"
WScript.Quit
End If
If the script runs in 32 bit mode on 64 bit windows, it re-runs itself in 64 bit mode.
Credit

Multi-purpose Module to update accdb records called in different userforms (using respective txtboxs)

I am creating an EXCEL VBA front-end system to manage a back-end Access (ACCDB) through ADODB connection.
I have been creating a single procedure to import, amend or create records in my back-end database for every userform, and i would like to tidy it and create a procedure in a Module to Call and name the objects and parameters where to get the information from.
Something like this:
In module:
Sub AddNewRecord(TABLE as string, INPUTFRM as
userform, DBPATH as string, DBPASS as string, SH as worksheet)
Dim rs As ADODB.Recordset
Dim cnn As ADODB.Connection
Dim sql As String
Set cnn = New ADODB.Connection
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBPATH & ";" &
"Jet OLEDB:Database Password=" & DBPASS
Set rs = New ADODB.Recordset
rs.Open Source:=TABLE, ActiveConnection:=cnn, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
Options:=adCmdTable
rs.AddNew
For i = 1 to 10
rs(SH.cells(1, i).value) = INPUTFRM.Controls("txtbox" & i).Value
Next i
rs.update
rs.close
cnn.close
Set rs = Nothing
Set cnn = Nothing
End Sub
In my Userform where i input the data:
Private Sub cmdAdd_Click()
Call AddNewRecord("ProjectsTable", Me.Name, ThisWorkbook.Path, "Pass1234", "Sheet1")
End Sub
My biggest problem is passing values from the textbox in the userform to the module. I am trying to pass the userform name to be used in the module when extracting the values in the different TextBoxes.
As in this section of the stored procedure.
Where in the first row of my sheet i have 10 field names (e.g.: ID, FirstName, LastName etc) and updated the respective fields based on the row.
The values to be updated will be contained in the 10 textboxes Userform that i Call the stored procedure.
For i = 1 to 10
rs(SH.cells(1, i).value) = INPUTFRM.Controls("txtbox" & i).Value
Next i
The reason i want to make this stored procedure is that i will be using in several different forms SQL queries based on some of the inputs in those forms and would be nice to have a cleaner and smaller code.
I am sorry if it doesn't look so clear in my sample code, is that i just created this sample code as an example of what i would like to perform.
If you guys know how to pass the Userform object value to be used in the Module or even know a workaround i would really appreciate if you'd share it.
Thank you very much,
Access doesn't have stored procedures. It has queries, but queries are limited to updating one table at a time. So that part is plain impossible.
There is one really hacky way to get stored procedure-like functionality (to update multiple tables at once) in Access: use data macros. Data macros are not intended for this purpose, and will make you unable to use the table you're setting these macro's on in a normal way. But you can use a "fake" table with data macros that updates other tables after insert, and then deletes it's own content.
You can pass a userform pretty easily, though:
In the userform:
Private Sub cmdAdd_Click()
AddNewRecord "ProjectsTable", Me, ThisWorkbook.Path, "Pass1234", "Sheet1"
End Sub
You will have to adjust to use the actual database path.

Use WMI query in VBA to get list of open files on local computer

As per title. Using this code example (3rd example down) as my starting point.
Here's my effort at VBA code, but it stalls at the first hurdle ("Run time error 438: object doesn't support this property or method")
Sub Test()
Set objConnection = GetObject("WinNT://HM10")
Set colResources = objConnection.Resources
For Each objResource In colResources
Debug.Print objResource.Path
Next
End Sub
HM10 is my computer name. Eventually it will need to be an environmental variable (if that's the right term) for whatever machine it happens to be on.
EDIT: Ok, more searching has led me to this:
Sub test()
Filename = "."
Set wmi = GetObject("winmgmts://./root/cimv2")
qry = "SELECT * FROM Win32_Process WHERE CommandLine LIKE '%" & Filename & "%'"
For Each p In wmi.ExecQuery(qry)
Debug.Print p.commandline
Next
End Sub
which is closer, but only shows local files, not network files. I only need network files, how do I get them?

How to copy data from non-linked to linked table in Access 2010 using VBA

So what I'm trying to do is to either copy data from an Access local table to a linked table on a SQL Server. I'd like this to work via a macro so it can be triggered upon opening a report. Or I could just bypass the linked table and insert directly to the remote server.
What I'm having a difficult time finding is the proper syntax to accomplish this. It should be very easy but apparently it's not.
Public Sub CopyPT()
Dim strSQL As String
Dim strConnect As String
Dim strDatabase As String
Dim strTableName As String
ODBC_String = "ODBC;DRIVER={SQL Server};SERVER=aaa;DATABASE=bbb;UID=ccc;PWD=ddd;" _
& "LANGUAGE=us_english;TRUSTED_CONNECTION=No"
' Id also like to truncate the Destination table here too
strSQL = "SELECT * INTO dbo_DESTINATION_TABLE IN [" & ODBC_String & "]" _
& " FROM [ACCESS_LOCAL_TABLE];"
DoCmd.RunSQL strSQL
MsgBox "Success!"
End Sub
Either I need to get the proper format for the IN statement, which doesn't appear to have ODBC option, or I need another method to copy to the linked table. Such a simple copy and paste line by line macro - which I also can't find anywhere since most sane people would just write a query.
Thanks!

error on opening a csv file using a jet oledb connection in excel vba

First time I'm using stackoverflow so here goes...
I've been getting errors intermittently when I try to run a macro in excel which I use for pulling in data from a CSV file. The error normally goes away if I start a fresh session, but this time it's been particularly persistant. It basically errors on the .Open line below, giving me a "Run-time error '2147467259' (80004005) Unspecified error":
Public Sub LoadFile()
file_path = Range("FlatFileLocation")
Set oConn = CreateObject("ADODB.Connection")
strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & file_path & "; Extended Properties=""text;HDR=Yes;FMT=Delimited(,)"";"
oConn.Open strcon
.....
Other info:
1) the file I'm trying to access is not open by another user
2) I close my connections at the end of the sub. also, i just tried restarting my machine and the error happened the first time I tried running the file
3) When I open my session up without any of my existing addins it seems to work. Is there any way of checking whether there is some sort of addin conflict going on?
There were other posts that suggest using CSVReader. Questions I have before trying this route are:
1) can I use this CSVReader across multiple user machines? The problem I would have here is needing to install it on a number of machines. I might be able to put a file on a shared drive however.
2) Can I query the resultant file with a SQL string? At the moment I use something like this:
....
strsql = "SELECT * FROM ( " & strsql & " ) WHERE ( ABS(PrevRisk) + ABS(CurrRisk) >= " & RiskThreshold & " ) ;"
Set oResult = New ADODB.Recordset
oResult.Open strsql, oConn
....
Thanks in advance for your help!