Excel VBA dump SQL Query into Array not to ListObject - sql

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

Related

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')

VBA error 13 : Type mismatch

I am new to VBA.
I am trying to extract all columns from other file but the result is displayed with error 13. How can I solve it?
Sub generate_data()
Application.CutCopyMode = False
Sheets("Output").Activate
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array(Array( _
"ODBC;DSN=HKGHKGT_UBET;Description=HKGHKGT_UBET;UID=SiuH;Trusted_Connection=Yes;APP=Microsoft Office 2016;WSID=HKHKDNO304NB;DATABASE=" _
), Array("UBet")), Destination:=Range("$A$1")).QueryTable
'CommandType = 0
.CommandText = Array("select * from UBet..cathy_fin where duns_no in(" & Sheets("Main").Range("A2").Value & ") order by stmt_date desc")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "HKGHKGT_UBET"
.Refresh BackgroundQuery:=False
End With
ActiveSheet.ListObjects("HKGHKGT_UBET").TableStyle = ""
Columns("B:B").Select
Selection.NumberFormat = "m/d/yyyy"
End Sub

Dynamic URL with QuertyTables.Add VBA

I'm trying to download data from a weather website (weather.gov) and trying to use variables for the latitude and longitude in the URL. If I go to the website and switch out the latitude and longitude manually, I will be directed to the correct city's weather forecast. However, when I try to set the latitude and longitude as a variable and combine the part of the URL that doesn't change with the variables for each city, it give me a compile error, Expected: list separator or ). It keeps getting stuck on this section ("&lon=-") in the URL. I'm not sure if there's a better way to declare the variable or add them in, but it doesn't make much sense to me why it doesn't like that middle section. Code below. Thanks!
P.S. The cityLat and cityLong variables would be values based on the city, but for right now I just have the actual latitude and longitude just to test it with.
Sub forecast_weather()
Dim cityLon As String
Dim cityLat As String
cityLat = "41.8781"
cityLong = "87.6298"
ActiveWorkbook.Worksheets("Chicago Weather").Select
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;http://forecast.weather.gov/MapClick.php?lat="&cityLat&"&lon=-
"&cityLong&"&unit=0&lg=english&FcstType=text&TextType=2", _
Destination:=Range("$A$1"))
.Name = "q?s=usdCAd=x_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
You need spaces around the &
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;http://forecast.weather.gov/MapClick.php?lat=" & cityLat & _
"&lon=" & cityLong & "&unit=0&lg=english&FcstType=text&TextType=2", _
Destination:=Range("$A$1"))
this gets Chicago weather
Sub forecast_weather()
Dim cityLon As String
Dim cityLat As String
cityLat = "41.8781"
cityLong = "-87.6298"
With Worksheets("sheet1").QueryTables.Add( _
Connection:="URL;http://forecast.weather.gov/MapClick.php?" _
& "lat=" & cityLat _
& "&lon=" & cityLong _
& "&unit=0&lg=english&FcstType=text&TextType=2", Destination:=Range("$A$1"))
.Name = "q?s=usdCAd=x_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

How to NOT refresh backgroundQuery vba

Does anyone know how to stop the refresh query table to constantly refreshing and only refresh itself once. he constant refresh, is making my excel spreadsheet run slow.
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;" & FilePath, _
Destination:=temp.Range("A1"))
.Name = "Deloitte_2013_08"
' .CommandType = 0
.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
Change this line:
.BackgroundQuery = True
to:
.BackgroundQuery = False
Use Application.ScreenUpdating to wrap your code.
application.screenupdating = false
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;" & FilePath, _
Destination:=temp.Range("A1"))
.Name = "Deloitte_2013_08"
' .CommandType = 0
.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
application.screenupdating = true
You might also be interested in setting Application.Calculation to xlCalculationManual before a large operation and then setting it to xlCalculationAutomatic after you are done.

Import query results into tool through 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
.