0

我有以下 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 中的特定单元格中,我不知道该怎么做。有没有人这样做过?

谢谢

4

1 回答 1

0

以下文章提供了不同的方法来实现这一点:http: //support.microsoft.com/kb/246335

于 2013-07-18T10:19:32.283 回答