I aim to bring the data from a Stored Procedure to a worksheet in Excel. This Stored Procedure is using two parameters for the query.
Excel 2013
SQL Server
What I have
I mounted a macro that queries the database, updates a table with the result of the query (Data) and then updates the PivotTable (ViewHistorico). Here is the code:
Sub Atualizar()
Dim lDataIni As String
Dim lDataFim As String
'Obtem os dados do parêmetro para consulta
lDataIni = "'" & Format(Sheets("ViewHistorico").Range("C1").Value, "yyyyMMdd HH:mm:SS") & "'"
lDataFim = "'" & Format(Sheets("ViewHistorico").Range("C2").Value, "yyyyMMdd 23:59:59") & "'"
Sheets("Dados").Select
'executa a consulta na planilha Dados para popular a tabela
With ActiveWorkbook.Connections("Query from dbDW").ODBCConnection
.BackgroundQuery = False 'False para forçar a espera da atualização do PowerPivot
.CommandText = Array("EXEC SpHistoricoCobrancaProdutor " & lDataIni & " , " & lDataFim)
.CommandType = xlCmdSql
.Connection = Array(Array( _
"ODBC;DRIVER=SQL Server Native Client 11.0;SERVER=dbDW;UID=efritsch;Trusted_Connection=Yes;APP=Microsoft Office 2013;WSID=C3" _
), Array("1089;DATABASE=DW;"))
.RefreshOnFileOpen = False
.SavePassword = False
.SourceConnectionFile = ""
.SourceDataFile = ""
.ServerCredentialsMethod = xlCredentialsMethodIntegrated
.AlwaysUseConnectionFile = False
End With
With ActiveWorkbook.Connections("Query from dbDW")
.Name = "Query from dbDW"
.Description = ""
End With
ActiveWorkbook.RefreshAll
'Atualiza o PowerPivot com base na planilha Dados que foi atualizadas
Sheets("ViewHistorico").Select
ActiveSheet.PivotTables("PivotTable2").PivotCache.Refresh
MsgBox ("Atualizado com sucesso!")
End Sub
What I want
I would like when creating a macro button I can automatically update my PivotTable without having to have another table. At this point I'm not getting it, I'm not able to develop a VBA code that makes it possible to update only the PivotTable with Stored Procedure query data.