Sub Get_Data_Loop_Named_Range()
'Team codes and years in named range 'Teams' (2 columns, n rows excluding column headers, on Sheet3). Web data is retrieved
'for each team code and year to next available row on Sheet2
Dim teamsRange As Range
Dim webDataSheet As Worksheet
Dim teamCell As Range
Dim webQuery As QueryTable
Dim destinationRow As Long, row As Long
Set teamsRange = Range("Teams")
Set webDataSheet = Sheets("Sheet2")
webDataSheet.Cells.ClearContents
For row = teamsRange.row To teamsRange.row + teamsRange.Rows.Count - 1
With webDataSheet
destinationRow = .Cells(Rows.Count, "A").End(xlUp).row
If destinationRow <> 1 Then destinationRow = destinationRow + 2
.Activate
.Range("A" & destinationRow).Select
'Copy team code and year to data sheet
teamsRange.Item(row, 1).Resize(1, 2).Copy .Range("A" & destinationRow)
destinationRow = destinationRow + 1
'Retrieve web page data for this team code and year
Set webQuery = .QueryTables.Add(Connection:="URL;http://www.baseball-reference.com/teams/" & _
teamsRange.Item(row, 1).Value & "/" & teamsRange.Item(row, 2).Value & "-schedule-scores.shtml", _
Destination:=Range("A" & destinationRow))
With webQuery
.Name = "schedule-scores.shtml"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlSpecifiedTables
.WebFormatting = xlWebFormattingNone
.WebTables = """team_schedule"""
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
webQuery.Delete
DoEvents
End With
Next
'Remove all column header rows except row 1 from web data sheet
destinationRow = Cells(Rows.Count, "A").End(xlUp).row
For row = destinationRow To 2 Step -1
If Cells(row, "A").Value = "Rk" And Cells(row, "B").Value = "Gm#" Then
Rows(row).Delete Shift:=xlUp
End If
Next
Cells(Rows.Count, "A").End(xlUp).Select
End Sub