我是Excel VBA的初学者,非常感谢您的帮助。
请建议如何创建Open和数据库连接的通用功能,以及关闭它的另一个功能,以避免重复编码?
这是我的代码。我一直坚持如何继续......
Const connection_string As String = "Provider=SQLOLEDB.1;Password=XXX;Persist Security `Info=True;User ID=sa;Initial Catalog=TESTDB;Data Source=XXXX;"
Sub DuplicateDBConnection()
'Declare variables
Set cn1 = New ADODB.Connection
Set cmd1 = New ADODB.Command
Set rs1 = New ADODB.Recordset
'Open Connection
cn1.ConnectionString = connection_string
cn1.Open
'Set and Excecute SQL Command
Set cmd1.ActiveConnection = cn1
cmd1.CommandText = "Select stock_code, name, sector_id from stock_master"
cmd1.CommandType = adCmdText
cmd1.Execute
'Open Recordset
Set rs1.ActiveConnection = cn1
rs1.Open cmd1
'Copy Data to Excel
ActiveSheet.Range("A1").CopyFromRecordset (rs1)
'Close Connection
rs1.Close
cn1.Close
'Throw Object
Set rs1 = Nothing
Set cn1 = Nothing
End Sub
我希望编写常用函数,这样我就不需要继续编写代码来连接和关闭连接。
Sub ConnectDB()
'Codes to connect DB
End Sub
Sub CloseConnnection()
'Codes to close connection
End Sub
Sub ExecuteCode()
ConnectDB
'Execute SQL command to manipulate data on excel and SQL database
CloseConnection
End Sub
根据Kittoe的建议编辑,现在正常工作。谢谢!
类别: 一个。创建了一个名为AdoDbHelper,Private Instancing的类 湾在AdoDbHelper中,将“选项比较数据库”更改为“选项比较文本”
模块: 创建这样的函数。
以下代码:
Const connection_string As String = "Provider=SQLOLEDB.1;Password=XXX;Persist Security `Info=True;User ID=sa;Initial Catalog=TESTDB;Data Source=XXXX;"
Sub Test()
Dim sourceDb As New AdoDbHelper
Dim sourceRs As New ADODB.Recordset
sourceDb.Connect (connection_string)
Set sourceRs = sourceDb.OpenRecordset("Select stock_code, name, sector_id from stock_master")
With sourceRs
'Do stuff!
ActiveSheet.Range("A1").CopyFromRecordset sourceRs
.Close
End With
sourceDb.Disconnect
Set sourceRs = Nothing
Set sourceDb = Nothing
End Sub
答案 0 :(得分:5)
这种类型的东西最好在课堂上完成。右键单击“IDE”中的VBA项目,然后转到Insert - >课程模块。为你的课命名一些有意义的东西,比如clsAdoHelper(如果匈牙利符号是你的东西),AdoDbHelper,或其他东西。以下是您在此课程中输入的代码示例:
Option Compare Database
Option Explicit
Private WithEvents conn As ADODB.Connection
Private WithEvents rs As ADODB.Recordset
Public Sub Connect(ConnectionString As String)
If Not conn Is Nothing Then
Debug.Print "A connection is already open."
Exit Sub
End If
If ConnectionString = CurrentProject.Connection.ConnectionString Then
Set conn = CurrentProject.Connection
Else
Set conn = New ADODB.Connection
conn.Open ConnectionString
End If
End Sub
Public Sub Disconnect()
If Not conn Is Nothing Then
If conn.State <> 0 Then
conn.Close
End If
Set conn = Nothing
End If
End Sub
Public Sub Execute(SQL As String)
If conn Is Nothing Then
Debug.Print "No connection open."
Exit Sub
End If
conn.Execute (SQL)
End Sub
Public Function OpenRecordset(SQL As String, Optional CursorLocation As ADODB.CursorLocationEnum = adUseClient, Optional CursorType As ADODB.CursorTypeEnum = adOpenForwardOnly, Optional LockType As ADODB.LockTypeEnum = adLockReadOnly) As ADODB.Recordset
If conn Is Nothing Then
Debug.Print "No connection open."
Exit Function
End If
If Not rs Is Nothing Then
Debug.Print "A recordset is already open."
Exit Function
End If
Set rs = New ADODB.Recordset
With rs
.CursorLocation = CursorLocation
.CursorType = CursorType
.LockType = LockType
.Open SQL, conn
End With
Set OpenRecordset = rs
End Function
Public Sub BeginTransaction()
conn.BeginTrans
End Sub
Public Sub CommitTransaction()
conn.CommitTrans
End Sub
Public Sub RollbackTransaction()
conn.RollbackTrans
End Sub
Private Sub conn_BeginTransComplete(ByVal TransactionLevel As Long, ByVal pError As ADODB.Error, adStatus As ADODB.EventStatusEnum, ByVal pConnection As ADODB.Connection)
Debug.Print "Transaction started."
End Sub
Private Sub conn_CommitTransComplete(ByVal pError As ADODB.Error, adStatus As ADODB.EventStatusEnum, ByVal pConnection As ADODB.Connection)
Debug.Print "Transaction committed."
End Sub
Private Sub conn_ConnectComplete(ByVal pError As ADODB.Error, adStatus As ADODB.EventStatusEnum, ByVal pConnection As ADODB.Connection)
End Sub
Private Sub conn_Disconnect(adStatus As ADODB.EventStatusEnum, ByVal pConnection As ADODB.Connection)
End Sub
Private Sub conn_ExecuteComplete(ByVal RecordsAffected As Long, ByVal pError As ADODB.Error, adStatus As ADODB.EventStatusEnum, ByVal pCommand As ADODB.Command, ByVal pRecordset As ADODB.Recordset, ByVal pConnection As ADODB.Connection)
Debug.Print "SQL execution complete."
End Sub
Private Sub conn_RollbackTransComplete(ByVal pError As ADODB.Error, adStatus As ADODB.EventStatusEnum, ByVal pConnection As ADODB.Connection)
Debug.Print "Transaction rolled back."
End Sub
使用新课程
Dim sourceDb As New AdoDbHelper
Dim sourceRs as New ADODB.Recordset
sourceDb.Connect (<insert connection string here>)
Set sourceRs = sourceDb.OpenRecordSet(<insert SQL string here>)
With sourceRs
'Do stuff!
.Close
End With
sourceDb.Disconnect
Set sourceRs = Nothing
Set sourceDb = Nothing
这不是我写过的最好的代码,但它应该给你一个不错的开始。如果您无法理解课程的工作原理,我鼓励您对VBA中的OOP和课程进行一些研究。您会注意到这里仍然有一些必要的biolerplate代码,但是在类方法中已经为您完成了大部分正常工作。如果您想将数据操作逻辑放入它自己的函数中,您可以将使用该类创建的ADODB.Recordset对象传递给它(这将替换WITH
块)。
我不建议使用这样的逻辑来污染类,因为您希望类处理任何可能的ADODB连接的所有通用连接/断开/异常处理。这样你就可以在其他项目中重复使用它= D.
答案 1 :(得分:1)
使用Microsoft ActiveX数据对象库x.x:
在您的VBA窗口中,转到工具&gt;参考文献&gt; Microsoft ActiveX数据对象库x.x
我通常使用2.7来向下兼容。现在,您可以创建ADODB对象以打开连接,执行查询(选择/更新/删除/ ...),并将查询结果(称为记录集)用于Excel的其余部分,特定单元格中的表格。
为了确保始终使用相同的连接,请创建一个公共连接对象并在所有子例程中引用它。在每个子例程中,首先检查它是否已由(conn
作为我的ADODB.Connection
对象)设置:
If conn = Nothing Then Call Setup_Connection
Subroutine Setup_Connection就像:
Private Sub Setup_Connection
Dim strConnection as String
If conn = Nothing Then
'Choose your own database connection details
strConnection = "Provider=SQLOLEDB.1;Integrated Security=SSPI;" & _
"Persist Security Info=False;" & _
"Initial Catalog=DatabaseName;" & _
"Data Source=DATABASESERVER"
Set conn = New ADODB.Connection
With conn
.Open strConnection
.CommandTimeout = 30
End With
End If
End Sub