Option Explicit
'Handle multiple query tables on this sheet
Private Sub Worksheet_Change(ByVal Target As Range)
Dim qt As QueryTable
Dim nextColumn As Long, dataRow As Long
Dim i As Integer
If QueryTables.Count = 0 Then
MsgBox "There isn't a web query defined on the '" & Sheet2.Name & "' sheet"
Exit Sub
End If
Debug.Print "Target " & Target.Address
'Determine which web query caused the change
Set qt = Nothing
i = 1
While i <= QueryTables.Count And qt Is Nothing
If Not Intersect(QueryTables(i).Destination, Target) Is Nothing Then
Set qt = QueryTables(i)
Debug.Print "Matched "; i, QueryTables(i).Destination.Address
End If
i = i + 1
Wend
If Not qt Is Nothing Then
Debug.Print "Copy "; qt.Destination.Address
'Row to copy the data to on Sheet1 is the same as the web query destination row
dataRow = qt.Destination.row
With Sheet1
If .Cells(dataRow, 1).Value = "" Then
'Copy web data field names (in column A) to column A on Sheet1
Range(Cells(qt.ResultRange.row, qt.ResultRange.Column), _
Cells(qt.ResultRange.row + qt.ResultRange.Rows.Count, qt.ResultRange.Column)).Copy .Cells(dataRow, 1)
End If
'Determine next available column in dataRow
nextColumn = .Cells(dataRow, Columns.Count).End(xlToLeft).Column + 1
'Copy web data column B to dataRow and next column on Sheet1
qt.ResultRange.Offset(, 1).Copy .Cells(dataRow, nextColumn)
End With
End If
End Sub
Private Sub CommandButton1_Click()
Dim i As Integer
If QueryTables.Count > 0 Then
For i = 1 To QueryTables.Count
If Not QueryTables(i).Refreshing Then
Debug.Print "Refresh "; i
QueryTables(i).Refresh BackgroundQuery:=True
DoEvents
End If
Next
End If
End Sub