Skip to content

Instantly share code, notes, and snippets.

@atifaziz
Created February 27, 2014 13:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atifaziz/9249699 to your computer and use it in GitHub Desktop.
Save atifaziz/9249699 to your computer and use it in GitHub Desktop.
Add or update an Excel WebQuery
Function AddOrUpdateWebQuery(ByVal URL As String, Optional DontRefresh As Boolean = False) As QueryTable
Dim Connection As String: Connection = "URL;" & URL
Dim PostText As String: Dim Parts() As String
If Len(URL) > 1024 Then
' URL exceeds 1K so use HTTP POST to get around the limit
Parts = Split(URL, "?", 2)
URL = Parts(LBound(Parts))
If UBound(Parts) > LBound(Parts) Then PostText = Parts(UBound(Parts))
End If
On Error Resume Next
Dim QueryTable As QueryTable: Set QueryTable = ActiveCell.QueryTable
On Error GoTo 0
If QueryTable Is Nothing Then
Set QueryTable = ActiveSheet.QueryTables.Add(Connection:=Connection, Destination:=Selection)
With QueryTable
If Len(PostText) > 0 Then .PostText = PostText
.BackgroundQuery = True
.TablesOnlyFromHTML = True
.SaveData = True
End With
Else
QueryTable.Connection = Connection
End If
If Not DontRefresh Then QueryTable.Refresh BackgroundQuery:=False
Set AddOrUpdateWebQuery = QueryTable
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment