如何在连接数组字符串中指定数据库用户凭据 (Excel VBA)

how to specify database user credentials in a connection array string (Excel VBA)

请帮助修改连接数组字符串 (Excel 2010) 以便能够接收来自字段 UID=;PWD=Initial Catalog.[=15= 的单元格引用的输入]

.Connection= Array("OLEDB;Provider=MSDASQL.1;Persist Security Info=True;Extended Properties=""DSN=NZSQL;Database=consumerdb;Servername=192.54.97.102;", "UID=USERNAME;PWD=****;Port=5480;ReadOnly=0;SQLBitOneZero=0;LegacySQLTables=0;NumericAsChar=0;ShowSystemTables=0;LoginTimeout=0;QueryTimeout=0;DateFormat=1;SecurityLevel=preferredUnSecured;CaCertFile="";Initial Catalog=CONSUMERDB_USERNAME")

Connection 字符串是一个简单字符串数组。您需要找到包含用户名和密码的部分,然后将该部分分开并插入单元格中的值。将连接字符串的各个部分放在不同的行上以帮助分解它。如果有助于隔离您要操作的子字符串,请拆分每个部分。

.Connection = Array("OLEDB;Provider=MSDASQL.1;Persist Security Info=True;" & _
                    "Extended Properties=""DSN=NZSQL;Database=consumerdb;Servername=192.54.97.102;", _
                    "UID=USERNAME;PWD=****;" & _
                    "Port=5480;ReadOnly=0;SQLBitOneZero=0;LegacySQLTables=0;NumericAsChar=0;" & _
                    "ShowSystemTables=0;LoginTimeout=0;QueryTimeout=0;DateFormat=1;" & _
                    "SecurityLevel=preferredUnSecured;CaCertFile="";Initial Catalog=CONSUMERDB_USERNAME" _
                   )

现在很容易找到用户名和密码并将值连接到该部分。

Dim usr As String, pwd As String
usr = Range("A1").Value
pwd = Range("B1").Value
.Connection = Array("OLEDB;Provider=MSDASQL.1;Persist Security Info=True;" & _
                    "Extended Properties=""DSN=NZSQL;Database=consumerdb;Servername=192.54.97.102;", _
                    "UID=" & usr & ";PWD=" & pwd & ";" & _
                    "Port=5480;ReadOnly=0;SQLBitOneZero=0;LegacySQLTables=0;NumericAsChar=0;" & _
                    "ShowSystemTables=0;LoginTimeout=0;QueryTimeout=0;DateFormat=1;" & _
                    "SecurityLevel=preferredUnSecured;CaCertFile="";Initial Catalog=CONSUMERDB_USERNAME" _
                   )