在运行VBA Excel时避免运行时身份验证错误

时间:2018-10-08 22:45:18

标签: excel vba excel-vba

这是我的代码,该代码使用具有用户名和密码字段的表单连接到Redshift。

If TextBox_username.Value = "" Or TextBox_password.Value = "" Then
       MsgBox "Enter Username and Password"
    Else
         oConn.Open "Driver={Amazon Redshift (x86)};" & _
            "Server=" & strServerAddress & ";" & _
            "Port=123;" & _
            "Database=abc;" & _
            "Uid=" & strUsername & ";" & _
            "Pwd=" & strPassword & ";"
        oConn.commandTimeout = 600

        If oConn.State = 1 Then
        End If
    End If

问题是,如果用户错误输入了错误的凭据,则会收到运行时错误,如下所示: enter image description here

如何通过显示“无效凭据”的消息来处理此错误,而不是给出运行时错误并要求结束?谢谢您的帮助

1 个答案:

答案 0 :(得分:3)

首先,您需要转到

Tools -> Options -> General -> Error trapping

然后选择

Break on Unhandled errors

添加到您的代码中:

Public Sub Teste()
On Error GoTo Err
    If TextBox_username.Value = "" Or TextBox_password.Value = "" Then
       MsgBox "Enter Username and Password"
    Else
       oConn.Open "Driver={Amazon Redshift (x86)};" & _
                "Server=" & strServerAddress & ";" & _
                "Port=123;" & _
                "Database=abc;" & _
                "Uid=" & strUsername & ";" & _
                "Pwd=" & strPassword & ";"
       oConn.commandTimeout = 600

       If oConn.State = 1 Then
       End If
    End If
Exit Sub
    Err:
    Msgbox Err.Description 'Your custom message
End Sub