使用输入参数执行存储过程并插入excel中的特定单元格

使用输入参数执行存储过程并插入excel中的特定单元格,excel,ado,vba,Excel,Ado,Vba,我有以下vba例程 Private Sub cmdStartDate_Click() 'Set Variables Dim conn As ADODB.Connection Dim str As String Dim exeStr As String Dim rs As ADODB.Recordset Dim fld Dim i As Integer Dim connStr As String Dim cmd As New ADODB.Command 'Error Handler On E

我有以下vba例程

Private Sub cmdStartDate_Click()

'Set Variables
Dim conn As ADODB.Connection
Dim str As String
Dim exeStr As String
Dim rs As ADODB.Recordset
Dim fld
Dim i As Integer
Dim connStr As String
Dim cmd As New ADODB.Command


'Error Handler
On Error GoTo errlbl

'Open the database connection
Set conn = New ADODB.Connection

'Construct the connection string
conn = "Driver={SQL Server};Server=10.50.50.140;Database=tbjc;UID=oe;PWD=Orth03c0"

'Open the connection
conn.Open

'Create the command object
Set cmd = New ADODB.Command


'Create and store the start date parameter
With cmd
    .CommandText = "dbo.cusUltrasoundReport"
    .CommandType = adCmdStoredProc
    .Parameters.Append .CreateParameter("@Start", adVarChar, adParamInput, 12, txtStartDate.Text)
    .Parameters("@Start").Value = txtStartDate.Text
    .ActiveConnection = conn
End With

'Create the recordset
Set rs = cmd.Execute

'str = txtStartDate.Text

'exeStr = "exec dbo.UltrasoundReport(" & str & ")"

'Open recordset
'rs.Open

If Not IsEmpty(rs) Then
    rs.MoveFirst

    'Populate the first row of the sheet with recordset's field name
    i = 0
    For Each fld In rs.Fields
        Sheet1.Cells(1, i + 1).Value = rs.Fields.Item(i).Name
        i = i + 1
    Next fld



    'Populate the sheet with the data from the recordset
    Sheet1.Range("A49:Q49").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
获取信息并将参数传递给存储过程就可以了

我需要它做的是将每个字段值插入excel中的特定单元格,我不知道该如何做。以前有人这样做过吗


谢谢你

下面的文章提供了不同的方法来实现这一点:

谢谢你这篇文章做得很好。我真不敢相信我没找到它。