1
votes

I've been encountering a sudden program crash when my MS Access database is not found. Can someone help me with my connectionstring.

here's the code :

    DoEvents
    Set con = New ADODB.Connection
    With con
    .ConnectionString = "Driver={Microsoft Access Driver (*.mdb)};Dbq=mydatabase.mdb;DefaultDir=C:\Projects\Database\;Uid=;Pwd="
    .CursorLocation = adUseClient
    .Open
    End With


I want to put code something like this...

   if connection = successful then
        continue to table query...
   else
        show message box
   endif 


2

2 Answers

1
votes

In order to detect a failed connection, you have to do error trapping.

' Start error trapping.
On Error Resume Next

Set con = New ADODB.Connection
With con
    .ConnectionString = "Driver={Microsoft Access Driver (*.mdb)};Dbq=mydatabase.mdb;DefaultDir=C:\Projects\Database\;Uid=;Pwd="
    .CursorLocation = adUseClient
    .Open
End With

' Check for error.
If Err <> 0 Then
    ' Error.
    Msgbox("Error during connection.")
Else
    ' Success.
End If

' End error trapping.
On Error GoTo 0
1
votes

You can use error handling like this:

On Error Goto ConErr

Set con = New ADODB.Connection  
With con
.ConnectionString = "Driver={Microsoft Access Driver (*.mdb)};Dbq=mydatabase.mdb;DefaultDir=C:\Projects\Database\;Uid=;Pwd="
.CursorLocation = adUseClient  
.Open
End With

' here insert query code or Goto statemen '

Exit sub
ConErr:
MsgBox "connection error"