Opening a workbook with ADODB connection in a second session in Excel - vba

The problem only exists when I open the workbook in a new Excel session and there are other sessions open before
No problem when I open the workbook in the same Excel session as the first Excel session
The problem is that something breakes down:
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
strFile = ThisWorkbook.FullName
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
cn.Open strCon
When the last line i.e. cn.open strCon above is executed there opens a read only version of the workbook in the first Excel session and everything breakes down.
This is very strange because it is another session in which the read only version pops up in.
I have seen some people complaining about this issue without a solution e.g.:
http://www.ozgrid.com/forum/showthread.php?t=76156

The best solution I've found so far is to check whether the workbook is open prior to connecting to it. This way there is no reason for the error condition to occur. It does require you to close the connection once you are finished accessing data so that other users can access it. You can use the code in https://stackoverflow.com/a/9373914/453475 to check whether a workbook is locked.
This works in my case as I can connect in, write the data and close the connection after it's written. The plus side is that I know that there aren't two users writing at the same time so there should be no possible conflicts.
I haven't tested how this works if using a read only connection. I'd hope that if you are opening a book read only that you shouldn't have to worry about this limitation but I need to research this more first.

Related

Running SQL Within An Open Workbook

I'm trying to use VBA to perform some SQL operations within an open workbook. If I open the file as a read only (i.e. from an email) the code runs without issue, but if I save it locally to my desktop I get a run-time error "Cannot update. Database or object is read-only". Below is a snippet of the code I'm trying to run
Set CSVconn = New ADODB.Connection
CSVconn.ConnectionString = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & ThisWorkbook.FullName & ";" & _
"Extended Properties='Excel 12.0 Xml;HDR=yes';"
CSVConn.Open
tmprs.ActiveConnection = CSVconn
tmprs.Source = "SELECT DISTINCT [X] FROM [Range]"
tmprs.Open
Range(X).CopyFromRecordset tmprs
CSVconn.Close
I believe the problem lies with the "ThisWorkbook.FullName" portion of the connection string since the code works on my coworkers' PCs and off our company drive. The file is saved locally and the "Files On Demand" setting for OneDrive is turned off, but the file path is still listed as running through https://sharepoint.com. I've used the split function to rebuild the SharePoint address as a local C drive one (which will open the workbook if I paste the address in file explorer), but running it in VBA throws an error that the file path is not valid. I've tried switching the connection to a GUID, but Windows shut down the Scriptlet.TypeLib function as a security measure and I can't seem to get their workaround code to run. Anyone know how to fix the CSVConnection issue or how to assign a randomly generated GUID to an open workbook using VBA?

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 Database connection error: Cannot open database '(unknown)'

I am trying to connect to Access Database using ADO DSN.
StrPath = Sheets("Sheet1").Range("DB_location")
strCon = "DSN=MS Access Database;DBQ=" & StrPath & ";"
Set con = New ADODB.Connection
con.Open strCon
I can connect to DB without any problem on my machine. However, when I tried running this exact macro on another PC, I ran into this issue on the last line:
I assumed it was due to Database Engine, but installing "Microsoft Access Database Engine 2010 Redistributable" from Microsoft's website didn't solve this problem. All the necessary references in VBA editor are present.
There is no problem with DB or the macro, as I checked on a different PC, but this specific computer runs into this problem.
Changing
strCon = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = " & StrPath & ";"
solved this problem, which means the problem was somehow due to DSN. Does anyone have a guess about where does this problem might come from?
I had this error and it ended up being my primary keys. WHen i fixed my primary keys in the table it worked like a charm.

Is it possible to know how many Oracle connections are opened in Excel VBA?

I have an excel macro. Macro is connecting to Oracle to fetch data.
This fetching may or may not open more than one connections (depending how users have coded inside macro).
Is it possible to know Oracle connections opened in excel vba ? or
I rephrase my question: Is it possible to know how many connections were opened from that Excel macro in VBA script ?
Connection Code:
Public Const CONNECT_STRING = "Provider=MSDAORA.1;Password=XXXX;User ID=XXXXX;Data Source=XXXXX;Persist Security Info=True"
Dim conn As ADODB.Connection
conn.Open CONNECT_STRING
MsgBox Application.ActiveWorkbook.Connections.Count
Count is still 0
The answer is no... and yes.
There is nothing built in to keep track of how many ADODB connections you have open to a particular database. You would have to keep track of this yourself if it is a requirement.
You could do this by adding each of your connections to a collection as you create them and then write a function to check two things before returning a count.
Make sure the connection object isn't Nothing
Make sure the connection is open before counting it by checking the connection's state property.
Dim conn As ADODB.Connection
For Each conn in someCollection
If Not conn Is Nothing Then
If conn.State <> adStateClosed Then
count = count + 1
End If
End If
Next conn
You're on your own to figure out how you want to actually track all of the connections in your project.

EXCEL ADODB Query on local worksheet not Including newly inserted records

I am using ADODB to query data form a worksheet in the Active workbook. The data resides on it's own sheet, and has column headers. I've defined the table as an excel ListObject - excel's automatic table formatting construct.
I open the connection like this:
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & ThisWorkbook.Path & "\" & _
ThisWorkbook.Name & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
cn.Open strCon
Then I can fetch a recordset using a simple SQL statement:
strSQL = "SELECT * from [sheet1$]
rs.Open strSQL, cn, 0, 1 'cursortype = adOpenForwardOnly, locktype = adOpenReadonly
This all works fine... until I insert a new row in the table on sheet1. The new row is not included in subsequent queries, even if I close, set to nothing, and re-open both the connection and recordset variables in my code.
If I save and close the workbook, and then re-open it, the new records ARE included in the query, which leads me to believe this might be a caching issue. I've searched for ADODB Cache Flush etc, but most results appear to be related to PHP or Access. I've also tried a variety of other options for Cursor Type and Lock Type, with no difference.
Can anyone suggest how I can ensure that each time I run my query I get all the rows, even after I insert new rows in the table?
Figured out a solution:
Since I'm using Excel 2010, I discovered that I can use a newer version of ADODB.
So, instead of defining my connection string like this:
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="...
I changed it to this:
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="...
and the problem is solved. New inserts and edits are now showing up immediately after I make them. This also removes the issue of the known memory leak in OLEDB.4.0, so that's a bonus.