Reputation: 31
I currently have an API
fed into my excel
which downloads stock prices from a URL
. Column A2:A194
is the company name, B2:B194
are the corresponding stock prices.
I want to create a macro
which runs every 5 minutes, fetches new prices and pastes them into the adjacent column.
This is what i have been able to achieve so far:
[Sub GetPrice()
'
' GetPrice Macro
'
' Keyboard Shortcut: Ctrl+q
'
ActiveWorkbook.RefreshAll
ActiveCell.Offset(0, -1).Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
ActiveCell.Offset(0, 1).Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ActiveCell.Offset(-1, 0).Range("A1").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=NOW()"
ActiveCell.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ActiveCell.Offset(1, 0).Range("A1").Select
Application.CutCopyMode = False
ActiveCell.Offset(0, 1).Range("A1").Select
Application.OnTime Now + TimeValue("00:05:00"), "GetPrice"
End Sub]
This macro pulls data from the previous column instead of B2:B194
. How do I change the same?
Eg: At the end of 1 hour, I would want 14 columns to have data: the original 2 + 12 columns with fetched price every 5 minutes.
Upvotes: 0
Views: 1031
Reputation: 2477
Along the lines of why it's pulling from the previous column. It's because you are using Offset instead of declaring which columns you want to use specifically. If you know it's going to be:
Sheets("Sheet1").Range("B2:B194")
then just edit the macro where it defines that part.
The macros are a great way to get an idea of what is going on in the code, but I'd always edit them to be more efficient or just easier to read. Mainly, because so much of the macros depend on the user clicking and activating cells constantly, which isn't necessary for a value to be inserted somewhere or a function to be executed. You can also see everything going on in the background very quickly, looking questionable.
Upvotes: 1