为什么不使用 ssis 包或 ssrs 报告进行数据提取?宏是如此......上个世纪。
如果你坚持使用宏,这里有一个例子:
Dim con As ADODB.Connection, _
cmd As ADODB.Command, _
rs As ADODB.Recordset, _
strSQL As String, _
i As Integer
strSQL = "EXEC SP_StoredProcedureToGetData"
Set con = New ADODB.Connection
con.Open "Provider=SQLOLEDB;Data Source=SQLSERVER;" & _
"Initial Catalog=DATABASE;User ID=USERNAME;Password=PASSWORD"
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = con
.CommandText = strSQL
.CommandType = adCmdStoredProc
End With
Set rs = New ADODB.Recordset
With rs
.CursorLocation = adUseClient
.CursorType = adOpenKeyset
.LockType = adLockBatchOptimistic
End With
Set rs = cmd.Execute
Cells(1, 1) = "Column1"
Cells(1, 2) = "Column2"
Cells(1, 3) = "Column3"
Cells(1, 4) = "Column4"
Cells(1, 5) = "Column5"
Cells(2, 1).CopyFromRecordset rs
Set con = Nothing
Set cmd = Nothing
Set rs = Nothing