I want to import a live data server from Microsoft SQL Server with time filter but in Excel and a refresh button.
To be more exact, I want to create a user friendly program in Excel where you can enter 2 parameter values of time (StartDate
and EndDate
).
I saw some video on YouTube with what I want, but every time I finish, I get this error
Error 1004 – Application-Defined or Object-Defined Error
I see this site: https://www.automateexcel.com/vba/error-1004-application-defined-object-defined/
But I don t know what I need to change.
This is SQL command for time:
select top 10000 *
from [IAG_Machine1].[dbo].[PD_Report]
where tist between '1/31/2023 4:02:06 PM' and '2/20/2023 4:02:06 PM'
AND [PrNr] = '2'
order by tist
In Excel, I have this code:
Sub RunQuery()
ActiveWorkbook.Queries("Query1").Formula = "let" & Chr(13) & "" & Chr(10) & " Source = Sql.Database(""***IP****"", ""IAG_Machine1"", [Query=""#(lf)select top 10000 * #(lf)from [IAG_Machine1].[dbo].[PD_Report]#(lf)#(lf)where tist between '" & ActiveSheet.Range("$E$2") & "' and '" & ActiveSheet.Range("$E$3") & "'#(lf)AND [PrNr] = '" & ActiveSheet.Range("$E$1") & "'#(lf)order by tist ""])" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " Source"
ActiveWorkbook.Queries("Query1").Refresh
End Sub