我对此很陌生。我正在尝试在 VBA 中编写一个从 excel 执行存储过程并返回记录集的过程。它目前在电子表格 2 中返回存储过程的结果,但我不得不将参数硬编码到 SQL 代码中。这是我从其他在线论坛中摘录的内容。
Option Explicit
Public Sub OpenConnection()
'Set the variables
Dim conn As ADODB.Connection
Dim str As String
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim fld
Dim i As Integer
'Error handler
On Error GoTo errlbl
'Open database connection
Set conn = New ADODB.Connection
'First, construct the connection string.
'ODBC CONNECTION YOU'VE ALREADY SET UP:
conn.ConnectionString = "DSN=PC_Tool_Coding"
conn.Open 'Here's where the connection is opened.
Debug.Print conn.ConnectionString 'This can be very handy to help debug!
'Recordset
Set rs = New ADODB.Recordset
str = "exec Select_account_info"
'recordset is opened here
rs.Open str, conn, adOpenStatic, adLockReadOnly
If Not IsEmptyRecordset(rs) Then
rs.MoveFirst
'Populate the first row of the sheet with recordset’s field names
i = 0
For Each fld In rs.Fields
Sheet2.Cells(1, i + 1).Value = rs.Fields.Item(i).Name
i = i + 1
Next fld
'Populate the sheet with the data from the recordset
Sheet2.Range("A2").CopyFromRecordset rs
Else
MsgBox "Unable to open recordset, or unable to connect to database.", _
vbCritical, "Can't get requested records"
End If
'Cleanup
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
exitlbl:
Debug.Print "Error: " & Err.Number
If Err.Number = 0 Then
MsgBox "Done", vbOKOnly, "All Done."
End If
Exit Sub
errlbl:
MsgBox "Error #: " & Err.Number & ", Description: " & Err.Description, vbCritical, "Error in OpenConnection()"
Exit Sub
'Resume exitlbl
End Sub
我已经环顾四周如何让它与参数一起工作,但我似乎无法到达那里。我将使用的参数在 SQL 中称为 @accgrpnum。它是一个 12 个字母的字符串。
非常感谢提前提供的任何帮助。