如何在VBA中用MsgBox显示连接失败或账号密码错误的错误(-2147217843)
Got it, let's tweak your VBA code to show a clear MsgBox specifically for that -2147217843 error (which typically points to invalid username/password or a failed connection attempt) instead of looping through errors and printing them to the debug window. Here's how you can do it:
Modified Code Snippet
Else ' Handle connection errors Dim errObj As Error Dim foundTargetError As Boolean foundTargetError = False ' Loop through connection errors to find the specific code For Each errObj In objConn.Errors If errObj.Number = -2147217843 Then MsgBox "Connection failed: Invalid username/password or unable to reach the server.", _ vbExclamation, "Connection Authentication Error" foundTargetError = True Exit For ' Exit loop early once we've found our target error End If Next ' Fallback for unexpected errors If Not foundTargetError Then MsgBox "An unexpected error occurred: " & objConn.Errors(0).Description, _ vbCritical, "Unexpected Error" End If End If
Key Details
- We specifically check for the error code
-2147217843(this is the standard ADODB error for login/connection failures) - The
Exit Forstatement stops the loop as soon as we find the target error, making the code more efficient - We added a fallback message for any other unexpected errors, so you don't leave users without feedback
- The
vbExclamationandvbCriticalicons help users quickly recognize the severity of the issue
内容的提问来源于stack exchange,提问作者abinaya
相关产品推荐
相关产品推荐

