I am trying to convert an app from 2003 VB to 2010 - vb.net

I opened the older app in VS 2010 and made changes based on the recommendations in the error statements that popped up. However one part that is still not working is shown below.
The error that comes back is
"file is already opened exclusively by another user or you need permission to view it"
I am opening up an access database and " select" and put it in an excel worksheet. The name of the worksheet changes every time the app is used.
This worked in 2003 but not in 2010. I have goggled this and none of the answers have worked.
Dim AccessConn8 As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=c:\UpdateExportFile\ExportFile.mdb")
AccessConn8.Open()
Dim AccessCommand8 As New System.Data.OleDb.OleDbCommand("SELECT * INTO [Excel " & _
"5.0;DATABASE=c:\" & strfilename & ".xls;HDR=YES;].[sheet1] from ExcelExport", AccessConn8) '
Try
AccessCommand8.ExecuteNonQuery()
Catch exe As DataException
Catch exc As System.Exception
MsgBox("EXCEL not updated. Contact your System Administrator. " & strfilename)
MsgBox(" ----> " & exc.Message)
AccessConn8.Close() ' added sat 2/23/15
Exit Sub
End Try
AccessConn8.Close()
Dim obook As Microsoft.Office.Interop.Excel.Workbook
Dim oexcel As Microsoft.Office.Interop.Excel.Application
oexcel = CType(CreateObject("Microsoft.Office.Interop.Excel.Application"), Microsoft.Office.Interop.Excel.Application)
obook = oexcel.Workbooks.Open("c:\" & strFileName & ".xls")
Try
With oexcel
.Visible = False
.Range("C1").Value = "'Store #"
.Range("D1").Value = "'Vendor #"
End With
Catch ex As Exception
MsgBox("error:" & ex.ToString, MsgBoxStyle.Critical, "ERROR")
End Try
' added
Dim myrange As Excel.Range
myrange = oexcel.Range("a1:l90")
myrange.Sort(Key1:=myrange.Range("c1"), Order1:=Excel.XlSortOrder.xlAscending, Header:=Microsoft.Office.Interop.Excel.XlYesNoGuess.xlYes, Orientation:=Excel.XlSortOrientation.xlSortColumns)
obook.Save()
obook.Close()
oexcel.Quit()
Can you help me downed the right path to an answer?

I cannot be sure but I suspect that this behavior is caused by connection pooling that keeps the connection (and perhaps the file) open also after you have tried to close it.
I suggest two changes to your code above, all around the connectionstring and the way in which you open close the connection
Using AccessConn8 As New OleDbConnection("...;OLE DB Services = -2;")
AccessConn8.Open
......
' Code as above....
......
End Using
The OLE DB Services = -2 disables the automatic use of Connection Pooling for this connection, while the Using Statement ensures that the connection is closed and DISPOSED after you have finished to use it

Related

Need some help diagnosing SEHException External component has thrown an exception

Windows Forms application using VB.Net and VS2012. Connecting to an Access database using Access Runtime 2013. The app is compiled to target x86. The problem is intermittent and occurs on multiple different PC's randomly, and accessing a database on a local hard drive.
Using cn As New OleDbConnection
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
If Not OpenDBConnection(cn) Then
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
MsgBox("Unable to make database connection to update screen status.", MsgBoxStyle.OkOnly, "Database Connection Error (MMUN1)")
Exit Sub
End If
'continue processing....
end using
Public Function OpenAccessConnection(ByRef conn As OleDb.OleDbConnection) As Boolean
Dim builder As New OleDbConnectionStringBuilder()
'conn.Provider = "Microsoft.ACE.OLEDB.12.0"
Try
builder.ConnectionString = "Data Source=" & DPATH & DBNAME
builder.Add("Provider", "Microsoft.ACE.OLEDB." & ACCESSVER & ".0") 'ACCESSVER is '12'
conn.ConnectionString = builder.ConnectionString
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
conn.Open()
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
Return True
Catch ex As Exception
MsgBox("Unable to make Access connection. Error# " & Err.Number & " " & ErrorToString() & " " & ex.ToString, MsgBoxStyle.OkOnly, "Database Connection Error (OLEOPN1)")
Return False
Finally
builder.Clear()
builder = Nothing
End Try
End Function
Public Function OpenDBConnection(ByRef conn As OleDbConnection) As Boolean
'I know this is an extraneous function call but it is in transition from multiple prior uses and I thought I had better not exclude it from this post in case it mattered for some reason
OpenDBConnection = OpenAccessConnection(conn)
End Function
Error being returned intermittently:
I have read many of the posts on this topic and have not found a solution, and frankly am not sure where to look. Could this be coming from an earlier application error? Thread/STA issue? If so, what do I do about it? On the development machine, I will on occasion see a DisconnectedContext error, but have not seen the External component error which appears on PC's running the released version. Are these related? Also, there are some ADO (ADODB) connections being made to the database (still trying to replace/upgrade), but these are not open at the time this new connection is being made. But could it be a connection pooling issue? Thanks in advance for any help out there.

Trying to make a connection to QODBC, Import a table, and then close the connection

Working in Access 2007 in VBA:
Basically what I have currently works without errors but I no I'm probably violating something within the code (adodb and DAO possibly?), regardless I can't get the connection to end when the code finishes. If I remove the code for the "import," then the connection does start, executes whatever code, then shuts off which is what I'm looking to do but with an import.
My reasoning for doing this is the QODBC accesses a user account that goes into Quickbooks and then extracts the information. Problem is that the "user" basically stays logged in which isn't good because we need access to single user mode and what have you. Here is the code I have so far. Please help!
Private Sub Connect_Click()
On Error GoTo ErrorHandler
'*****************************************************
'Connects the DB to QODBC, imports, and queries the info
'*****************************************************
Dim msg As String
Dim oConnection
Dim sConnectString
Dim dbs As DAO.Database
Dim lngRowsAffected As Long
'Sets connection string
sConnectString = "DSN=Quickbooks Data;OLE DB Services=-2;"
Set oConnection = CreateObject("ADODB.Connection")
oConnection.Open sConnectString
Set dbs = CurrentDb
' Import from QODBC
DoCmd.TransferDatabase acImport, "ODBC Database", "ODBC;DSN=QuickBooks Data;DFQ=C:\Users\Public\Documents\Intuit\QuickBooks\Sample Company Files\QuickBooks 2012\sample_manufacturing business.QBW;SERVER=QODBC;OptimizerDBFolder=%AppData%\QODBC Driver for QuickBooks\Optimizer;OptimizerCurrency=Y;OptimizerAllowDirtyReads=D;OptimizerSyncAfterUpdate=Y;SyncFromOtherTables=N;ForceSDKVersion=<default SDK>;LicenseYear=2018", acTable, "SalesOrder", "SalesOrder1"
'Executes a query that appends a table called 'SalesOrder' from a table called 'SalesOrder1'
dbs.Execute "qryAppendSalesOrder", dbFailOnError
'Bypasses warning messages through an execution of query but this grabs the total appended
lngRowsAffected = dbs.RecordsAffected
'Function that logs how many lines were appended. Basically just an activity table
Globals.Logging "Sales Orders Appended: " & lngRowsAffected
'Updates the 'SalesOrder' from 'SalesOrder1'
dbs.Execute "qryUpdateSalesOrder", dbFailOnError
'Deletes the 'SalesOrder1' table that was imported
DoCmd.DeleteObject acTable, "SalesOrder1"
lngRowsAffected = dbs.RecordsAffected
'Closes Connection
oConnection.Close
Set oConnection = Nothing
ErrorHandler:
If Err.Number <> 0 Then
msg = "Error # " & Str(Err.Number) & " was generated by " _
& Err.Source & Chr(13) & "Error Lne: " & Erl & Chr(13) & Err.Description
MsgBox msg, , "Error", Err.HelpFile, Err.HelpContext
End If
End Sub
oConnection.Open - 1st Connection is opened to QuickBooks Data.
DoCmd.TransferDatabase - 2nd Connection is opened to QuickBooks Data.
oConnection.Close - 1st Connection is Closed
When you use DoCmd, MS Access will open the connection to DSN=QuickBooks Data and will not close it until your close MS Access application.
There is an active connection to QODBC DSN & QuickBooks and thus, you are not able to close QuickBooks application.
You may have to close the MS Access application to release the connection.
Manually Close ODBC DSN Connection
Or Find a way to close the connection opened via DoCmd [DoCmd.Close() - does not close the connection]
Or use oConnection to transfer data from QODBC tables to MS Access tables. Read each row and add it to your MS Access table.
For more help, please create a support ticket or do a search for this issue at our support system page:
http://support.qodbc.com

Excel VB Database connection test

I have an excel spreadsheet with a bit of VB code that copies the data across to a access database. This copies the data from one sheet to a cache sheet and then from the cache sheet to the db using a flag to identify new data, This works ok but we would like to add a connection test to check if the connection to the database is ok.
This is the code i have below for the connection test:
Dim cnn As ADODB.Connection
Dim canConnect As Boolean
Set cnn = New ADODB.Connection
cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & _
"Data Source=\\G-FILE1\Common_Files\All Users\Robert T\Cash Sheets\CashSheets.mdb;"
If cnn.State = adStateOpen Then
canConnect = True
cnn.Close
MsgBox "Connection UP", vbOKOnly
Else
cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & _
"Data Source=\\G-FILE1\Common_File\All Users\Robert T\Cash Sheets\CashSheets.mdb;"
cnn.Close
If cnn.State = adStateClosed Then
canConnect = False
cnn.Close
MsgBox "Connection DOWN!", vbOKOnly
End If
End If
So what I want to do is this:
When button clicked > data is sent to cache sheet (Working) > Test DB connection > If not available, then msgbox user informing them > carry on caching sheet
I dont want the error window to appear, rather a msgbox and let the rest of the code carry on..
Hope this edit is a bit clearer..
Regards
It is enough if the file is available:
If Dir(accessFilePath) = "" Then
'file not found!
else
'file found!
end if

Querying Excel by multiple users - Need suggestion

I am seeking one suggestion on how to build an excel macro for below requirement. Request you to provide your valuable comments in EXCEL Only.
Scenario
I have one spreadsheet "Product Master" that contains all the product details.
(i.e. Product ID,Product Name,Product Type,Quantity etc etc)
I am designing a UserForm using excel VBA where anyone can fetch all the details of a product based on its Product ID. Now the product-master sheet where all the product details is present will get updated on a daily basis. And each user should be able to update any details in that sheet based on his requirement.
Questions/Doubts
How do I design my system? I mean where should I put my "Product-Master" spreadsheet so that it can be accessed by multiple users. What I am thinking is to put product-masster on a shared_drive so that all can access that sheet through VBA userform. I will provide excel VBA userform macro to everyone in my office & they will query that sheet present in shared drive. does this seem ok?
Does excel provide facility to Query data from sheet present in shared-drive & update it when required. And I want this to be queried by multiple users at a time.
I know there are other products/technologies that provides better solution than EXCEL. But I want the solution in EXCEL ONLY.
I would appreciate it if anyone can provide his/her valuable comments on this. Let me know in case you need any details.
Thanks you.
Here are some example functions getting data from/posting data to MS Access (took me awhile to dig these up, hah!). This uses a Reference to the Microsoft DAO 3.6 Object Library and will only work with legacy .mdb files, not accdb (because the mdb driver is 100x faster and doesn't have a memory leak.)
Const DBPath As String = "Full\Database\Path"
Function GET_ACCESS_DATA(DBPath, SQL) As Object
Dim dbConn As Object
Dim dbRS As Object
Dim SQL As String
On Error GoTo ErrorHandler
SQL = "Sql Query"
'Set up database connection string
Application.StatusBar = "Connecting to Database..."
'Open database connection
Set dbConn = OpenDatabase(DBPath)
'Run the query
Application.StatusBar = "Running Query..."
Set dbRS = dbConn.OpenRecordset(SQL, DAO.dbOpenForwardOnly, DAO.RecordsetOptionEnum.dbReadOnly)
'If no rows returned, display error message and exit
If dbRS.RecordCount = 0 Then
Application.StatusBar = "Running Query...Error"
MsgBox "There are no records for the selected criteria.", vbInformation, "Refresh Data"
Application.StatusBar = "REFRESHING DATA PLEASE WAIT.."
Exit Function
End If
'returns DAO Recordset with the data
Set GET_ACCESS_DATA = dbRS
'A recordset can either be looped through or pasted to a spreadsheet with the Worksheet.Range.CopyFromRecordset method
'Error trap here
End Function
Function POST_TO_ACCESS() As Boolean
POST_TO_ACCESS = False
errormod = "TRACKING"
On Error GoTo ERROR_TRAP:
'START CONTROLS
Application.StatusBar = "Formatting Data"
St_Timer = Timer 'start connection timer
Dim cn As DAO.Database
Set cn = DAO.OpenDatabase(DBPath)
En_Timer = Timer 'get connection time
'SetKey Parameters
UserNM = Replace(User_Name(), Chr(39), "")
CompNm = Environ("COMPUTERNAME")
Elapsed_Time = En_Timer - St_Timer
SQL = "INSERT INTO TBL_TRACKING " & _
"(UserNM) " & _
" VALUES ('" & UserNM & "')"
cn.Execute SQL
cn.Close
'END CONTROLS
Application.StatusBar = False
POST_TO_ACCESS = True
'error trap here
End Function
Function User_Name()
'This just gets the LDAP username of whoever is logged in. Useful for tracking. Not guarenteed to work for your Active Directory :)
Dim WshNetwork
Dim objAdoCon, objAdoCmd, objAdoRS
Dim objUser, objRootDSE
Dim strDomainDN, strUserName, strUserFullName
strUserFullName = ""
Set WshNetwork = CreateObject("WScript.Network")
strUserName = WshNetwork.UserName
Set objRootDSE = GetObject("LDAP://rootDSE")
strDomainDN = objRootDSE.Get("defaultNamingContext")
Set objAdoCon = CreateObject("ADODB.Connection")
objAdoCon.Open "Provider=ADsDSOObject;"
Set objAdoCmd = CreateObject("ADODB.Command")
Set objAdoCmd.ActiveConnection = objAdoCon
objAdoCmd.CommandText = _
"SELECT ADsPath FROM 'LDAP://" & strDomainDN & "' WHERE " & _
"objectCategory='person' AND objectClass='user' AND " & _
"sAMAccountName='" & strUserName & "'"
Set objAdoRS = objAdoCmd.Execute
If (Not objAdoRS.EOF) Then
Set objUser = GetObject(objAdoRS.Fields("ADsPath").Value)
objUser.GetInfoEx Array("displayName"), 0
strUserFullName = objUser.Get("displayName")
Set objUser = Nothing
User_Name = strUserFullName
Else
End If
Set objAdoRS = Nothing
Set objAdoCmd = Nothing
objAdoCon.Close
Set objAdoCon = Nothing
Set objRootDSE = Nothing
Set WshNetwork = Nothing
End Function

Compacting Database Error Message

When I am trying to compact my Access 2010 database (no password), I am getting the error message Class Not Registered I am using Visual Studio 2010, and I have not idea what this problem is. Here Is the code i'm using:
Private Sub Compactdb()
Dim JRO As JRO.JetEngine
JRO = New JRO.JetEngine
'The first source is the original, the second is the compacted database under an other name.
JRO.CompactDatabase("Provider=Microsoft.Jet.OLEDB.5.0;Data Source=C:\Forte\Ex.mdb; Jet OLEDB:Engine Type=5", "Provider=Microsoft.Jet.OLEDB.5.0;Data Source=C:\Forte\Temp.mdb; JetOLEDB:Engine Type=5")
'Original (not compacted database is deleted)
System.IO.File.Delete("C:\Forte\Ex.mdb")
'Compacted database is renamed to the original databas's neme.
Rename("C:\Forte\Temp.mdb", "C:\Forte\Ex.mdb")
'User notification
MsgBox("The database was compacted successfully")
End Sub
If I change the Jet.OLEDB.5.0 to 4.0 I get a different error message of Unrecognized databse format
Try
Dim ParentCNN As String
Dim CloneCNN As String
Dim JrO As New JRO.JetEngine
ParentCNN = "PROVIDER = MICROSOFT.ACE.OLEDB.12.0;DATA SOURCE = C:\Forte\Fortedb.accdb;JET OLEDB:DATABASE PASSWORD = 21061975;"
CloneCNN = "PROVIDER = MICROSOFT.ACE.OLEDB.12.0;DATA SOURCE = C:\Forte\Temp.accdb;JET OLEDB:DATABASE PASSWORD = 21061975;Jet OLEDB:Engine Type=5"
'If cnnMDE.State = ConnectionState.Open Then
' cnnMDE.Close()
'End If
JrO.CompactDatabase(ParentCNN, CloneCNN)
If System.IO.File.Exists("C:\Forte\Temp.accdb") Then
System.IO.File.Delete("C:\Forte\Fortedb.accdb")
Rename("C:\Forte\Temp.accdb", "C:\Forte\Fortedb.accdb")
End If
Catch ex As Exception
MainTextBox.AppendText(Environment.NewLine & "Database Compression Failure :" & vbCr & ex.Message)
End Try