Preparing the connection check to the SQL sever, which gives me below error if not in our group network its obsoletely fine but simple msgbox sufficient for me
Sub ADOExcelSQLServer()
Dim Cn As ADODB.connection
Dim server_name As String
Dim database_name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Dim ws As Worksheet
Set rs = New ADODB.Recordset
Set ws = ActiveSheet
server_name = "192.168.x.xxx\SQLEXPRESS"
database_name = "ABC_System"
User_ID = "xx"
Password = "12345"
SQLStr = "SELECT * FROM dbo.Tbl_anb"
'SQLStr = "dbo.Tbl_wid"
Set Cn = New ADODB.connection
Cn.Open "Driver={SQL Server};Server=" & server_name & ";Database=" & database_name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
If Cn.State = 1 Then
Debug.Print "Connected!"
MsgBox "Connected"
Else
MsgBox "Not Connected"
End If
CodePudding user response:
Here is modified version with On error:
Dim Cn As ADODB.connection
Dim server_name As String
Dim database_name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Dim ws As Worksheet
Set rs = New ADODB.Recordset
Set ws = ActiveSheet
server_name = "192.168.x.xxx\SQLEXPRESS"
database_name = "ABC_System"
User_ID = "xx"
Password = "12345"
SQLStr = "SELECT * FROM dbo.Tbl_anb"
'SQLStr = "dbo.Tbl_wid"
Set Cn = New ADODB.connection
On error resume next
Cn.Open "Driver={SQL Server};Server=" & server_name & ";Database=" & database_name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
on error Goto 0
If Cn.State = 1 Then
Debug.Print "Connected!"
MsgBox "Connected"
Else
MsgBox "Not Connected"
end if