2014-02-28 11 views
0

我有一个代码来打开表单时检查访问和sql server之间的连接。如果有连接,则弹出一个消息框并说明。如果没有,应该有一个消息框指示没有连接。相反,我得到的错误:其他部分的代码保持超时

Run Time Error '-2147467259 (80004005)': 
[DBNETLIB][ConnectionOpen (Connect()).]Specified SQL Server Not Found 

这是不是我想要它做的事,是东西在我的编码或者是有没有办法得到这个工作?

Public Sub AutoExec() 
Dim cnn As ADODB.Connection 
Dim localrst As New ADODB.Recordset 
Dim remoterst As New ADODB.Recordset 

Set cnn = New ADODB.Connection 
cnn.Open "Provider=SQLOLEDB; Data Source=DB; Initial Catalog=HRLearnDev;" _ 
& "User Id=ID; Password=PW;" 

If cnn.State = adStateOpen Then 

MsgBox ("You have an established connection with the L&TD SQL Server Database.") 
Else 
MsgBox ("Cannot connect to remote server. Data will be stored locally to CDData Table until application is opened again.") 

End If 

cnn.Close 



End Sub 

回答

2

在这样的情况下,你通常要使用On Error GoTo结构 - 如果发生错误,然后将代码发送到您的错误处理程序(可以测试,以确保该错误号是您期望与Err.Num什么) 。

但是,在你的情况下,它可能更容易使用On Error Resume Next。这告诉解释者“如果发生错误,请转到下一行,我会弄清楚出了什么问题并处理它。”

通常,当您有一个函数调用会产生错误或合理的值时,您会这样做。我经常这样做:

On Error Resume Next 
returnValue = -1 
returnValue = functionThatReturnsPositiveValue() 
If returnValue < 0 Then 
    MsgBox "oops - the function failed!" 
Else 
    ' <<<< do whatever needs doing >>>> 
End If 

在你的情况下,这几乎就是你会做的。完整示例:

Public Sub AutoExec() 
    Dim cnn As ADODB.Connection 
    Dim localrst As New ADODB.Recordset 
    Dim remoterst As New ADODB.Recordset 

    On Error Resume Next   ' <<<<<< add this line so an error doesn't stop the code 
    Set cnn = New ADODB.Connection 
    cnn.State = 0 ' <<<<< not sure if you need something like this, or if the New command 
         already set it to some sensible value other than "adStateOpen" 

    cnn.Open "Provider=SQLOLEDB; Data Source=DB; Initial Catalog=HRLearnDev;" _ 
    & "User Id=ID; Password=PW;" 

    If cnn.State = adStateOpen Then  ' <<<<<< this will only be true if no error occurred 
    MsgBox ("You have an established connection with the L&TD SQL Server Database.") 
    Else 
    MsgBox ("Cannot connect to remote server. Data will be stored locally to CDData Table until application is opened again.") 
    End If 
    On Error GoTo 0  ' <<<<<<<< turn off error handling - we have passed the "tricky" spot. 

' <<<<<< lots more code goes here >>>>>> 

    If cnn.State = adStateOpen Then cnn.Close ' <<<<<<<< only close connection if it was open!! 

End Sub 
+0

这看起来如何?我是一个新手,当涉及到这个东西 – user2119980

+1

我会编辑我的答案......我不知道你有多少知道。 – Floris

+0

工作很好,第二个窗口现在弹出。但是,当我单击确定时,我得到:运行时错误3704.当对象关闭时,操作不允许。它突出显示了代码的cnn.close部分。 – user2119980

相关问题