0

Let's skip to the command text box on the definitions tab of the connection properties.... my command type is SQL.

I can execute spDuplicatesAnalysis from within SSMS. I have tried a numbee things with no luck, including ...

exec spDuplicatesAnalysis
dbo.spDuplicatesAnalysis

So how should the actual command txt read ?

Thx!

4

1 回答 1

0

Calling stored procedures from Excel VBA

  1. Open a new Excel workbook
  2. Name one of the tabs "Data" (or change the code below)
  3. Open the VB Editor (Alt+F11)
  4. Add a new module
  5. Set a reference to Microsoft ActiveX Data Objects (choose highest version number available) Setting Reference to Microsoft ActiveX Data Objects
  6. Add the following code to your module

    Sub ExecStoredProcedureFromExcelVBA()
    
    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim connectString As String
    Dim custState As String
    Dim tgt As Worksheet
    
    Set tgt = ThisWorkbook.Sheets("Data")
    custState = "TX"
    
    ' Clear the target worksheet
    tgt.UsedRange.Clear
    
    ' Set the connection string
            connectString = "Provider=SQLOLEDB;Data Source=.;" & _
                 " Initial Catalog=Sandbox;Integrated Security = SSPI"
    
    ' Create the adodb objects
    Set cn = New ADODB.Connection
    Set rs = New ADODB.Recordset
    
    ' Open the connection and execute the stored procedure
    cn.Open connectString
    cn.spGetCustomersForState custState, rs
    
    ' Check for results
    If rs.state = 1 Then
        If Not rs.EOF Then
            ' Write the contents of the recordset to our target
            tgt.Range("a1").CopyFromRecordset rs
        rs.Close
        End If
    End If
    
    ' Clean up after ourselves
    If CBool(cn.state And adStateOpen) Then cn.Close
    Set cn = Nothing
    Set rs = Nothing
    
    End Sub
    
  7. Modify the module to reference the database, stored procedure, and parameters you want to work with

  8. Run the code
于 2012-09-15T21:42:20.523 回答