VBA - How to Clear a Connection String From a Connection

泄露秘密 提交于 2019-12-08 03:29:58

问题


I have a function that attempts to clear every connection string from every connection, it works as follows:

Public Sub RemovePasswordByNamePrefix()
    Dim w As Worksheet
    Dim qt As QueryTable
    Dim cn As Object
    Dim odbcCn As ODBCConnection
    Dim oledbCn As OLEDBConnection

    For Each cn In ThisWorkbook.connections
        If cn.Type = xlConnectionTypeODBC Then
            Set odbcCn = cn.ODBCConnection
            odbcCn.SavePassword = False

            odbcCn.connection = ""
            odbcCn.CommandText = ""

        ElseIf cn.Type = xlConnectionTypeOLEDB Then

            Set oledbCn = cn.OLEDBConnection
            oledbCn.SavePassword = False

            oledbCn.connection = ""
            oledbCn.CommandText = ""

        End If
    Next
End Sub

The issue is that this fails, with the following error(at the OLEDB section, connection = ""):

Run time error '1004'

Application defined or object-defined error

Attempting to do this by the interface doesn't work either, it's a little funky:

When you click the "OK" button, it just doesn't do anything... like the window doesn't close, no change, it's very strange. Actually this same behavior will persist unless you put something(valid or invalid) in the command text and command string sections...

Why is this the case? Is there a way to get around it? It's almost like MS put this as a "hidden" requirement and didn't document or provide feedback when the user/developer attempts to route around it.

The obvious question I'll receive on this is, why would I want to do this, I'll will open another ticket to address that, and add a link here


回答1:


Try instead; delete the connection and recreate later when you need it.

Public Sub RemovePasswordByNamePrefix()
    Dim w As Worksheet
    Dim qt As QueryTable
    Dim cn As Object
    Dim odbcCn As ODBCConnection
    Dim oledbCn As OLEDBConnection

    For Each cn In ThisWorkbook.Connections
        If cn.Type = xlConnectionTypeODBC Then
            cn.Delete
        ElseIf cn.Type = xlConnectionTypeOLEDB Then
            cn.Delete
        End If
    Next
End Sub


来源:https://stackoverflow.com/questions/53092637/vba-how-to-clear-a-connection-string-from-a-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!