Running VBS script from VBA - Unrecognized DB Format - vba

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

Related

How to resolve a connection problem when connecting SQL from VBA XLS " ; VBA error message= 'Not able to find ISAM file'

when setting and running ADODB connection to SQL from VBA xls, I got a error message "Not able to find the ISAM file", I writting the following connection in a VBA Module :
"Provider= Microsoft.ACE.OLEDB.12.0
"Data Source=" & PWRQRYFilePath
Im usiging xls 2019 , 32 bits. Referencing to Microsoft ActiveX Data Objects 6.1 Library.,
check any thing but not able to create and open the connection would you please help me.
Im trying to create and open the connection so I can run SQL queries from VBA xls
Following is a simple query i want to run to obtain a join inner from two spread sheets
But Actually the Query is sending me the error message.
What is the content of the variable PWRQRYFilePath?
For the sake of completeness:
If you want to go the long way, or better spoken, if you need the query more times, as you know, you can put the code lines also in a function an pass the path to the file to it.... here its represented by the Workbook-Property ThisWorkbook.Fullname
Dim rs As Object 'or AS ADODB.Recordset for EarlyBinding/IntelliSense
With rs
.Open "SELECT * FROM [worksheetname$] WHERE [column]='value'", _
";Provider=Microsoft.Ace.OLEDB.12.0" & _
";Extended Properties""Excel 12.0 xml""" & _
";Data Source=" & ThisWorkbook.FullName
'*** do your stuff with recordsetresult
.Close
End With
If you need the query just once, you can use a anonym function call as well:
With CreateObject("ADODB.Recordset")
.OPEN ...
'*** do your stuff ...
.CLOSE
End With

Closing connection to Excel spreadsheet in classic ASP using ODBC

Kind of a wordy title but I have a classic ASP application I am trying to write where a user uploads an Excel spreadsheet and then I take that spreadsheet and import the data into SQL.
I have everything working great but the one thing I'm running into is that after I open the spreadsheet using ODBC and close all the objects that reference it, if I try to delete the file, I get a permission denied error.
If I try to sweep the temp directory before uploading and I run into a previously uploaded file (say within the last two minutes), I get the permission denied error.
If I wait a minute or two, it seems like whatever lock was put on the file is released and I can delete it.
Here's some code:
sPath = Server.MapPath("/_temp/") & "\"
sFileName = Request.QueryString("filename")
Set objFile = Server.CreateObject("Scripting.FileSystemObject")
If objFile.FileExists(sPath & sFileName) Then
objFile.DeleteFile sPath & sFileName, True
End If
'Upload file occurs here
sConnectionString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & sPath & sFileName & ";"
adLockOptimistic = 3
sSQL = "SELECT * "
sSQL = sSQL & "FROM Range"
Set rsSystem = objExcel.Execute(sSQL)
'Do stuff
rsSystem.Close
Set rsSystem = Nothing
objExcel.Close
Set objExcel = Nothing
Set objFile = Nothing
Doesn't seem to matter if I try to delete the file before or after I do the import, if I try deleting the file right after a successful import, I get the permission denied error but if I wait a minute, I'm then able to delete it.
This is an issue as users are going to be supplied templates and they may make a correction and immediately re-upload.
Any ideas as to why the lock is not getting immediately released when I close all associated objects?
Thanks!
Edit:
Changing the connection string to use a different driver seems to have done the trick, now when I close the objects I can delete the file with no issue
sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sPath & sFileName & ";Extended Properties=Excel 8.0;"
I've actually found a number of ways to do this.
As stated in the comments of your OP, one option is to use SSIS and import your Excel spreadsheet using a stored procedure.
You can import directly using a stored procedure
Or use a check to test whether the file is locked

Automating access 2003 application

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)

Ms Access 2010 Recordset will not bind to combobox on some machines

I have an access 2010 database that was an access 2007 database. It uses a 2nd database on a network server.
I am developing in windows 7 32bit.
Below is the code I have inherited...
The problem I am having is that while the dataset binds to the combobox (Combo96) just fine for me in 'development mode' and in 'run mode' and it also works ok another windows 7 32bit machine and yet another windows 7 64bit machine. It refuses to work on one windows 32bit machine.
I'm guessing its a problem with references? All I know about the target (failing) machine is that is windows 7, it has the access 2010 runtime, it may have access 2007 or access 2007 runtime, I don't really have a way to find out.
I added the code at the bottom that takes the dataset and copies it to the combobox. This works just fine on all machines but takes considerably longer.
Any Ideas why the dataset wont bind to combo96 on some machines?
On Error GoTo err_hand
Dim SearchStr As String
Dim oRec As ADODB.Recordset
Combo96.RowSource = ""
txtSearch.SetFocus
SearchStr = Trim(txtSearch.text)
Set oRec = New ADODB.Recordset ' [Client Number],
strQuery = "SELECT replace(replace([Company],"","","""" ),"":"","""") as [Companys] FROM tblClient where company <> '' ORDER BY [Company] "
oRec.Open strQuery, Load_ribbon.get_Connection, adOpenKeyset, adLockOptimistic
Me.Combo96.RowSourceType = "Table/Query"
Set Me.Combo96.Recordset = oRec
oRec.Close
err_endit:
Set oRec = noting
Exit Sub
err_hand:
Call sendReport.SendErrorDetail("CMP-0701-" & Erl, "Can't Read [Clients] Data SRC-" & SearchStr & "-" & Err.Description & "-" & Err.Number)
' Here comes some Cheese!!!!
On Error GoTo Skippy
' Bounding probably failed Try manual
If Not (oRec Is Nothing) Then
If oRec.RecordCount > 0 Then
If oRec.RecordCount > 1000 Then
MsgBox ("Too amany records found please be more specific")
Else
Me.Combo96.RowSourceType = "Value List"
oRec.MoveFirst
Do While Not RS.EOF
Me.Combo96.AddItem RS![Company]
oRec.MoveNext
Loop
End If
End If
End If
Resume err_endit
Skippy:
MsgBox ("Run-Time Error CMP-0702-" & Erl & " Can't Read [Clients] Data")
Call sendReport.SendErrorDetail("CMP-0702-" & Erl, "Can't Read [Clients] Data SRC-" & SearchStr & "-" & Err.Description & "-" & Err.Number)
Resume err_endit
Consider using the SQL query in the Combo96.RowSource instead of Combo96.Recordset property. If tblClient is available locally after connection, in VBA set the combobox's rowsource to
SELECT replace(replace([Company],"","","""" ),"":"","""") as [Companys] FROM tblClient where company <> '' ORDER BY [Company].
Apparently, there are caveats with how to open an ADODB Recordset to assign it to a combobox/listbox. See this forum thread: Populate Combo box using recordset
It turned out this is a problem with the Access runtime. Because both 2007 and 2010 were installed it is necessary to choose which one Access should run under.

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!