代码之家  ›  专栏  ›  技术社区  ›  Digvijay Sawant

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

  •  2
  • Digvijay Sawant  · 技术社区  · 6 年前

    这是我使用包含用户名和密码字段的窗体连接到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 回复  |  直到 4 年前
        1
  •  3
  •   Jorge Ribeiro    6 年前

    首先你得去

    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
    
    推荐文章