Created
February 27, 2014 13:08
-
-
Save atifaziz/9249699 to your computer and use it in GitHub Desktop.
Add or update an Excel WebQuery
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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