如何在Excel VBA中创建ADO连接时命名ADO连接

时间:2015-11-17 11:18:31

标签: excel vba excel-vba ado

如何命名ADO与VBA的连接?使用以下VBA代码的ADO方法添加新连接,默认情况下命名为" Connection"或" Connection2"等。

Sub Make_ADO_Connection()
Sheets(2).Cells.ClearContents

Dim oCn As ADODB.Connection
Dim oRS As ADODB.Recordset
Dim ConnString As String
Dim SQL As String

strFile = ThisWorkbook.FullName
ConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
Debug.Print ConnString

Set oCn = New ADODB.Connection
oCn.ConnectionString = ConnString
oCn.Open

SQL = "select asdf1,asdf2,asdf5 from [Arkusz1$] where asdf1 is not null"

Set oRS = New ADODB.Recordset
oRS.Source = SQL
oRS.ActiveConnection = oCn
oRS.Open

'-------------------
'Here new connection is established with a name "Connection", I want to use a different name for it.
Set objListObject = ActiveWorkbook.Sheets(2).ListObjects.Add(SourceType:=xlSrcExternal, _
Source:=oRS, LinkSource:=True, _
TableStyleName:=xlGuess, Destination:=Sheets(2).Range("A1"))
objListObject.Refresh

If oRS.State <> adStateClosed Then
oRS.Close
End If

If Not oRS Is Nothing Then Set oRS = Nothing
If Not oCn Is Nothing Then Set oCn = Nothing

End Sub

我想在创建它时命名新的ADO连接,即&#34; MyConnectionName&#34;如果存在这样的连接则先检查。

编辑。我可以遍历连接:

Dim conn As WorkbookConnection
For Each conn In ActiveWorkbook.Connections
    Debug.Print conn.Name 'This name I want to set up
Next conn

我知道与名称的连接&#34;连接&#34;使用以下语句创建:

Set objListObject = ActiveWorkbook.Sheets(2).ListObjects.Add(SourceType:=xlSrcExternal, _
Source:=oRS, LinkSource:=True, _
TableStyleName:=xlGuess, Destination:=Sheets(2).Range("A1"))

objListObject.Refresh

1 个答案:

答案 0 :(得分:1)

要使用ADO创建与DB的连接,请使用以下内容:

Public Sub TestQueryInvokation()

Dim oCnn As New ADODB.Connection
Dim oCmd As New ADODB.Command

oCnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\TestDB.accdb;Persist Security Info=False;"

oCmd.ActiveConnection = oCnn
oCmd.CommandText = "Query1"
Call oCmd.Execute

End Sub

这与您在那里看到的连接内容不同。 如果使用Excel功能区导入数据,则会创建连接并维护指向数据库的链接,并将其放入您已显示的集合中。我过去遇到过这种方法的问题,建议你自己创建。

您需要对ADO库的引用。或者将所有内容输入为Object,您不需要引用。