Loop through date range, but skip down to next year
Here's one way to do it. Add a temporary sheet, import the data from the web
site, the bring the data into memory using array variables. Once you have it
in memory, you can do whatever you want with it, including adding it to
another worksheet in a different order.
In the example I assume that there are always 12 months, so I don't bother
to store the months in memory. Stick the example in a general VBA module and
run it. I left off the part of what you do with the data after you get it in
memory.
Option Explicit
Option Base 1
'
' This routine adds a temporary sheet to
' grab data from a URL table, then once the
' data are in memory, deletes the sheet.
'
Sub Grab_and_Reorder()
Dim i As Long, j As Long
Dim nRows As Long
Dim nYears As Long
Dim wsh As Worksheet
Dim theYears() As Integer, theData() As Double
'
Set wsh = ActiveWorkbook.Sheets.Add
'
' First grab the table of data and put in on
' the active worksheet.
'
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;http://tonto.eia.doe.gov/dnav/ng/hist/n9132cn2m.htm", _
Destination:=Range("A1"))
.Name = "n9132cn2m"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = True
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlSpecifiedTables
.WebFormatting = xlWebFormattingNone
.WebTables = "10"
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
'
' Delete any blank rows (those whose first cell is blank)
'
Range("A:A").SpecialCells(xlCellTypeBlanks).Entire Row.Delete
'
' Next, determine how much data you just grabbed.
'
ActiveSheet.Cells(1, 1).Select
nYears = ActiveCell.CurrentRegion.Rows.Count - 1 ' Ignore header row
'
' Grab the data and store in memory
'
ReDim theYears(nYears)
ReDim theData(nYears * 12)
'
For i = 1 To nYears
theYears(i) = ActiveSheet.Cells(i + 1, 1)
For j = 1 To 12
theData((i - 1) * 12 + j) = ActiveSheet.Cells(i + 1, j + 1)
Next j
Next i
'
wsh.Delete
Set wsh = Nothing
'
' Now reorder the data as you please...
'
End Sub
"Jason" wrote:
Thanks! My only problem with web queries, and I am sure there is an easy way
to get around this, is usually I need to the data in a different format than
the way it is after the web query import.
I am new to the programming side of Excel, so I am not sure if there is a
way to run the web query, then re-arrange it.
|