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

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

Related

Excel VBA Recordset SQL - No value given for required parameters

Whilst the title of this question is similar to other questions asked in the past, I could not via limited searching on Google or SE find an answer that helped me with my problem below.
I am trying to pick up data from an excel sheet for processing. After finding that a more complex SQL statement with a join gave an error, I looked deeper and found the following;
The below SQL statement runs fine:
SELECT [DNSHEET$].[DNS] FROM [DNSHEET$]
However the below SQL statement does not & this gives the error stated in title later.
SELECT [DNSHEET$].[DNK] FROM [DNSHEET$]
I use the code below for running either SQL statement - they are saved in sql1 which is defined as a string.
rs.execute(sql1), cn
Where rs is the Recordset and cn the connection.
cn is defined as:
Set cn = CreateObject("ADODB.Connection")
With cn
.provider="Microsoft.ACE.OLEDB.16.0"
.ConnectionString="Data Source=" & ThisWorkbook.Path & "\" & ThisWorkbook.Name & ";" & _ "Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
.open
End with
DNS and DNK headers are correctly named and match headers on DNSHEET sheet.
DNS is populated with string data, DNK contains integers from 1 to circa 25000.
Update: This issue has been worked around by closing and reopening the excel workbook. Then both of the SQL queries could run.
Hence another question is why this arises and how to find out what the cause of the problem is?

My oledb connection works on a workbook but not on the other

So i have this code in two different workbooks, two different files. They are even in the same folder in the same computer.
strFile = "Z:\service\climatizacion.mdb"
strCon = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & strFile
Set cn = CreateObject("ADODB.Connection")
cn.Open strCon
strSQL = "SELECT codigorep, cantidad, precio, descripcion FROM cotizacion WHERE codigorep = " & lngInput & ";"
Set rs = CreateObject("ADODB.RECORDSET")
rs.Open Source:=strSQL, ActiveConnection:=cn, CursorType:=adOpenDynamic, LockType:=adLockOptimistic
In one of the workbooks it works perfect, it selects all the data i need from the database.
On the other it gives me the Runtime error 3001 (The application is using arguments that are of the wrong type, are out of acceptable range, or are in conflict with one another) when I try to open the recordset.
I figured through this code that the connection was the problem (I may be wrong)
If cn.State = adStateOpen Then
MsgBox "connected"
Else
MsgBox "not connected"
End If
I cannot find the difference between these workbooks that can make this connection or the entire code work or make it stop working.
All the variables are declared, the tables exist, i can open them through access with no problems, the database is located on a pc on my local network.
The database is an mdb file, from access 97. And i'm running this on excel 2003, both workbooks, and both were created by me with the same excel 2003.
Thank you in advance for taking the time to read this :D

Excel VBA Late Bind to Access and SQL Insert

I am having a frustrating issue with late binding to MS Access from Excel VBA to execute a DML statement like Insert or Update. All of the data I use in vba comes from user defined Classes. I can query just fine but writing to the DB gets different errors each time I try a different way to do the same thing. Below are some links to the same/similar issues, however each is slightly out of context and therefore I could not get passed my problem.
Microsoft.ACE.OLEDB.12.0 Current Recordset does not support updating error received when trying to update access
Operation must use an Updateable Query / SQL - VBA
Update an excel sheet using VBA/ADO
Operation must use an updatable query. (Error 3073) Microsoft Access
https://msdn.microsoft.com/en-us/library/bb220954%28v=office.12%29.aspx?f=255&MSPPError=-2147217396
http://www.access-programmers.co.uk/forums/showthread.php?t=225063
My end goal is to simply execute a DML string statement and it has to use late binding. Mainly I get the 3251 error saying my connection is 'Read Only' or a missing ISAM when I add ReadOnly=0 to the connection string. Fyi, getProjectFile just returns a path to a file starting from the parent folder of my project. I am pretty sure I can just use the connDB.Execute so I only need SQL Insert, I don't want to query first because the queries will get fat quick. I also think something might be wrong with the enum params because the ExecuteOptions want bitmasks instead of just a Long and I don't really know how to do that. From most of my research, I kept getting referred to the LockType and/or cursor not being right. For my environment; Windows 8.1 64bit, MS Office 2010 32bit(required). Does anyone see what is wrong here?
Sub ADO_Tester()
Dim strSQL, strFile, strConnection As String
Dim connDB As Object
'late bind to the ADODB library and get a connection object
Set connDB = CreateObject("ADODB.Connection")
'Connect to the DB
strFile = Application.ActiveWorkbook.Path & "\" & "PortfolioDB.accdb"
strConnection = "Provider = Microsoft.ACE.OLEDB.12.0; data source=" & strFile & ";"
connDB.Open strConnection
'insert statement for a test record
strSQL = "INSERT INTO underlying_symbol (symbol) VALUES ('xyz')"
'execute the
connDB.Execute strSQL, , 2, 1 + 128
'clear the object
connDB.Close
Set connDB = Nothing
End Sub
Edit:
Early binding:
connDB.Execute strSQL, , adCmdText + adExecuteNoRecords
Late Binding: How to enter the value for adExecuteNoRecords? On msdn it is 0x80 and another post says &H0001,either way it gives a syntax error. It says enter a bitmask for this enum value.
connDB.Execute strSQL, , 1 + 0x80
Edit: Now the correct way -
adExecuteNoRecords (the ADO enum value) = 0x80 (a binary value) = 128 (a decimal value)
connDB.Execute strSQL, , 1 + 128
Edit: Now the issue gets even deeper. When I execute the code in a test spreadsheet into a test database, it works. When I copy and paste into the actual project spreadsheet and point to actual project db, I get the error: operation must use an updateable query . . . again. Same db name, same dml, same table name. The only difference is the actual DB is a product of a split to separate it from the forms and code in Access. Could this have changed some setting to make it read only?
Edit: It just gets deeper and deeper. The issue causing it not to work in the project db is because I have some Excel Tables querying the db. I made these through the Excel UI, Ribbon -> External Data -> Access -> etc. . . It has now become obvious these are causing me to be unable to insert DML because they are probably set to read only. How can I change the tables connections permissions? Is there another way I could be making these tables so that I can provide the connection? How to get Tables to be friendly with DML in VBA?
This worked for me:
Option Explicit
Private Const acCmdText As Integer = 1
Sub ADO_Tester()
On Error GoTo ErrorHandler
Dim strSQL As String
Dim strFile As String
'Dim adoRecSet As Object
Dim connDB As Object
'late bind to the ADODB library and get a connection object
Set connDB = CreateObject("ADODB.Connection")
'Connect to the DB
strFile = getProjectFile("core", "PortfolioDB.accdb")
connDB.Open connectionString:="Provider = Microsoft.ACE.OLEDB.12.0; data source=" & strFile & ";"
'If State = 1, db connection is okay.
MsgBox "ADO Connection State is " & connDB.State & "."
'SQL to get the whole [underlying_symbol] table
'strSQL = "underlying_symbol" 'if options 2
'strSQL = "SELECT * FROM underlying_symbol" 'if options 1
strSQL = "INSERT INTO underlying_symbol (symbol) VALUES ('xyz')"
'late bind to adodb and get recordset object
'Set adoRecSet = CreateObject("ADODB.Recordset")
'&H0001 = bitmask for aCmdText
connDB.Execute strSQL, , acCmdText
'With adoRecSet
' .Open Source:=strSQL, _
' ActiveConnection:=connDB, _
' CursorType:=1, _
' LockType:=3, _
' Options:=&H1
'.AddNew
'.fields("symbol") = "XYZ"
'.Update
'End With
'------------------
'close the objects
'adoRecSet.Close
connDB.Close
'destroy the variables
'Set adoRecSet = Nothing
Set connDB = Nothing
ExitMe:
Exit Sub
ErrorHandler:
MsgBox Err.Number & ": " & Err.Description
GoTo ExitMe
End Sub
Added some error handling, a constant that defines acCmdText (Why just not add a reference to ADO library? Up to you, though.), and a message box to check the connection state to the database, as I can't test your getProjectFile function. Late binding doesn't seem to be the issue here, I think the key line is:
connDB.Execute strSQL, , 2, &H1
Can really say what's going on here as I've never done it like this (code doesn't even compile), but changing it to
connDB.Execute strSQL, , acCmdText
worked for me.

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!

How to read excel file in vb.net 2003

Can anyone help me on how can I read the excel file using vb.net 2003?
The first thing to do is to browse the excel file in my vb.net program then read the content of excel file and display the value of excel content in listview.
The quickest and easiest way to read an Excel file in vb.net is to use the Jet database driver.
Set cnExcel = New ADODB.Connection
cnExcel.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & MyFilename & ";" & _
"Extended Properties=""Excel 8.0;IMEX=1;HDR=NO"""
Then read through it. Here I display columns 0 and 1
rs.Open "select * from " & MySheetName, cnExcel, adOpenDynamic, adLockOptimistic
While Not rs.EOF
debug.print rs(0)
debug.print rs(1)
rs.MoveNext
Wend
An alternate way to query for data inside an Excel spreadshet is to use the interop assemblies Microsoft has released for interacting with Office apps from .NET (2003 versions here).
Using these interops is a bit more involved and you need to be careful about properly releasing the Excel objects you create to avoid leaks, but does give you more access to all the information contained with the workbook you're opening - you can see a short intro for using these assemblies here.