VBA code to check if SQL Server exists

paulosq

New Member
Joined
Dec 13, 2012
Messages
2
Hi All,

I have an Excel workbook that retrieves data from a SQL Server database on the local network. When the computer is where the workbook is on the network, all right, but when not on the network, I get the message:


"Run-time error '-2147467259 (80004005)': [DBNETLIB] [ConnectionOpen (Connec ()).] SQL Server does not exist or access denied."​

I tried to treat this using On Error GoTo ErrHandler:, but the instruction is ignored.

I need that when the SQL server is not available, the application VBA ignore retrieve data and present the user with a message more friendly.

Please can someone help me?

I am using MS Excel 2010 64-bit with SQL Server 2008 R2 and my code to test the connection is this:

Sub TstCnn()

On Error GoTo ErrHandler:
Dim adoCnn As ADODB.Connection
Dim strCnn As String
Dim blnCnn As Boolean
strCnn = "Provider=SQLOLEDB.1;"
strCnn = strCnn & "Data Source=localhost;Initial Catalog=BD_Financial;"
strCnn = strCnn & "Integrated Security=SSPI;"
Set adoCnn = New ADODB.Connection
adoCnn.Open strCnn
If adoCnn.State = adStateOpen Then
blnCnn = True
adoCnn.Close
End If
MsgBox blnCnn

ExitHere:
On Error GoTo 0
Exit Sub

ErrHandler:
MsgBox "NOK"
Resume ExitHere:

End Sub


Many thanks and sorry for my bad English.

Paulo S. Quateli
 

Excel Facts

Bring active cell back into view
Start at A1 and select to A9999 while writing a formula, you can't see A1 anymore. Press Ctrl+Backspace to bring active cell into view.

Forum statistics

Threads
1,214,653
Messages
6,120,750
Members
448,989
Latest member
mariah3

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top