Import query results into tool through VB.NET - vb.net

I am writing a tool to import a database query results into Excel in VB.NET
I tried the following code. It is not working.
With objApp.ActiveSheet.QueryTables.Add(Connection:="ODBC;DSN=Build_statistics;", _
Destination:=objApp.Range("G15"))
.CommandText = "SELECT * from mytable"
.Name = "Query"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = Microsoft.Office.Interop.Excel.XlCellInsertionMode.xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
**.Refresh(BackgroundQuery:=False)** 'I am getting error here
End With
It is working fine in VBA, but not in VB.NET.

Why not load the query results into a DataSet and then import the contents of the DataSet table into Excel?

The line
**.Refresh(BackgroundQuery:=False)** 'I am getting error here
is not correct and should be replaced by
.Refresh BackgroundQuery:=False
.

Related

Excel VBA dump SQL Query into Array not to ListObject

I am creating a SQL query to get data from an SQL database, but the macro recorder posts the data into a listobject. I want the query to post the data into an array instead of listobject.
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Query1;Extended Properties=""""" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT * FROM [Query1]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Query1"
.Refresh BackgroundQuery:=False
End With

SQL statement too long in VBA

In order to have the completed SQL i stored it at one of the worksheets then extract from there, but having error if the statement too long as the vba not able to capturing the full SQL code (if the filter data is not alot it works fine). Im very new to use the SQL in the VBA and hope if there any way can solve for this
Please refer below code that i have created, Thanks. It will stop at the Commandtext = Array(SQLCODE) when requested too many data. Thanks
CODE1 = Worksheets("Sheet1").Range("A6")
SQLCODE = CODE1
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"ODBC;DSN=EBT-RAW;UID=00174;Trusted_Connection=Yes;APP=Microsoft Office 2016;WSID=SNG-LP-0153;DATABASE=EBTRawConsumption" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array(SQLCODE)
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Table_Query_from_EBT_RAW"
.Refresh BackgroundQuery:=False
End With
This is SQLCODE
Select * FROM EBTRawConsumption.dbo.AMI_UsageData
WHERE UsageDate >= '2019-6-1'and UsageDate <= '2019-7-1'
and MeterID in ('','000572992','000674117','000685835','000680646','000681342','000697973','000697890','000728193','000728213','000730270','000730266','000730800','000730267','000732442','000731276','000730869','000731890','000731592','000735403','000737161','000737976','000739532','000738001','000737581','000737596','000737996','000738298','000737587','000738840','000739370','000739367','000736241','000737089','000738970','000740763','000742172','000746989','000750232','000749300','000749303','000749179')

how to import data using .odc file in Excel 2013 VBA

I am trying to write some VBA that will import some data into a query table using a .odc file that is stored in a SharePoint data connection library. I used the macro recorder to record the process where I add the connection, then go to the existing connections and import the data into a table in the current worksheet(which worked when I did it manually).
The recorder spit out the following code (I removed the command text since it contains some sensitive info, but it was a big string of SharePoint related stuff like the list and view GUID):
Sub RecordedImportMacro()
Workbooks("MyWorkbook.xlsm").Connections.AddFromFile _
"http://path/to/my/odcfile/on/sharepoint.odc"
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Office.List.OLEDB.2.0;Data Source="""";ApplicationName=Excel;Version=12.0.0.0" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = 5
.CommandText = "some command text here"
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.SourceConnectionFile = "http://path/to/my/odcfile/on/sharepoint.odc"
.ListObject.DisplayName = "My_Table"
End With
End Sub
However, when I run the macro to seemingly perform the exact same task that worked before I get the following error: Run time error 1004. I googled and it didn't really find anything that pertained to my use case
when I debug the following line is highlighted: .CommandType = 5
Any ideas on how to get this working?
I was able to get it working using code found here
Below is the code:
Sub ThisWorks()
With ActiveSheet.QueryTables.Add(Connection:= _
"FINDER;http://path/to/my/odcfile/on/sharepoint.odc" _
, Destination:=Range("$A$1"))
.RefreshStyle = xlInsertDeleteCells
.RowNumbers = False
.FillAdjacentFormulas = False
.RefreshOnFileOpen = True
.HasAutoFormat = True
.BackgroundQuery = True
.TablesOnlyFromHTML = True
.Refresh BackgroundQuery:=False
.SavePassword = False
.SaveData = True
End With
End Sub

Fetch Website data into Excel

The most recent answer to Fetch Website data into Excel was:
Sub FetchData()
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;http://www.zillow.com/homes/comps/67083361_zpid", Destination:=Range( _
"$A$1"))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlEntirePage
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
End Sub
It works well for my project as well except the URL of my interest is:
URL;http://reservations.example.com/cp/reports/daily_usage.php?type=date_reservations&date=06%2F03%2F2015&date_end=&vessel=&club=6&location=135", Destination:=Range( _
"$A$1"))
I have used a fake URL above for privacy reasons, but as you can see, the URL has a date code within. In this case it is June 3rd, 2015 as designated by 06%2F03%2F2015.
Using VBA, how can I make the date within the URL a variable, defined within a work sheet?
With the Format() function most probably. A wild guess would be
Format(Range("$A$1").Value2, "mm""%2F""dd""%2F""yyyy")
You can also reconstruct it by yourself using the Day(), the Month() and the Year() functions and some playing around with IIf(Len(x)=2,x,0&x).
My sample gave "06%2F03%2F2014" for 2014-06-03.

Excel VBA - Return SQL Data To Excel Table

I am having a little trouble returning SQL data into an Excel table, instead of dropping the data into the cell I specify (when not using a table) it pushes the whole table to the right.
Does anyone know how I can get it to populate the table as I want to make use of splicers etc. to filter the data. I know I could import the data then turn it into a table but if there's a quicker, simpler way then I'd rather that.
Right now the code I'm using is:
With ActiveSheet.QueryTables.Add(Connection:="ODBC;DSN=<dbname>", Destination:=ActiveSheet.Range("A13"))
.CommandText = strSQL
.Name = "Query"
.FieldNames = False
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = False
.RefreshPeriod = 0
.PreserveColumnInfo = True
.Refresh BackgroundQuery:=False
End With
ActiveSheet.QueryTables(1).Delete
Many thanks in advance.
Dan