I have the following code to retrieve some data from a web-table.
Sub Retrieve_ticker_list()
Dim Stockticker As Long 'loopvalue (URL link) you want to use
Dim DownloadInfoSheet As Worksheet
Set DownloadInfoSheet = ActiveWorkbook.Worksheets("DownloadInfo")
Dim DataSheet As Worksheet
Set DataSheet = ActiveWorkbook.Worksheets("Data")
Dim lastrowStock As Long
Dim lastrowG As Long
Dim baseURL As String
Dim searchResultsURL As String
lastrowStock = DownloadInfoSheet.Cells(Rows.Count, "C").End(xlUp).Row 'Find last row in Stockticker
lastrowG = DataSheet.Cells(Rows.Count, "A").End(xlUp).Row + 10 'Find last row in range PART3
For Stockticker = 2 To lastrowStock 'Loop from page 2 to lastrow
baseURL = DownloadInfoSheet.Cells(2, "A") 'download from cell A2:
searchResultsURL = baseURL & DownloadInfoSheet.Cells(Stockticker, "C").Value 'Add the ticker symbol to the original URL link, example
With DataSheet _
.QueryTables.Add(Connection:="URL;" & searchResultsURL, Destination:=DataSheet.Range(DataSheet.Cells(1, "A"), DataSheet.Cells(lastrowG, "A")))
.Name = _
"Stock Data"
.BackgroundQuery = True
.RefreshStyle = xlOverwriteCells
.TablesOnlyFromHTML = True
.WebSelectionType = xlSpecifiedTables
.WebTables = """Rf"""
.PreserveFormatting = True
.Refresh BackgroundQuery:=False
Call Delete_Query_Content_Data 'See code below. I have tried to have this inside and outside the "with" loop
End With
Call RunProcess 'calculate adjusted key-ratios
Next Stockticker
End Sub
I got issues when I try to delete the connection. If the web table exists and is pasted into the workbook, then I can delete the connection with the below code without problem.
However, when the URL is incorrect (invalid stockticker name) the code works (paste blank data), but I'm not able to remove the connection. I can manually go to "Data" -> "Connections" -> "Remove" but it doesn't work with code. Either the connection is not removed (if lastrowG = 1
) or I get the following error (lastrowG = ... row + 10
):
Code to delete table query connection:
Sub Delete_Query_Content_Data()
' This code works when the URL code is valid, however if the code has an invalid stockticker (i.e. ADPA)
'it doesn't remove the connection (if I set lastrowG = 1) otherwise it mostly gives the error message 80010108
'Clear Web Query for "Stock data"
Sheets("Data").Activate
Range("A1").Select
Selection.QueryTable.Delete
Selection.ClearContents
End Sub
I have tried to replace Delete_Query_Content_Data
with suggestions from stackoverflow (example "Killing connection in EXCEL vba" and "Excel VBA Export to Excel - Removing Connections") but none of them solves my problem, I still get the error message.