简体   繁体   English

如何定期运行Excel宏并将更新的数据粘贴到新列中

[英]How to run excel macro periodically and paste updated data into new column

I currently have an API fed into my excel which downloads stock prices from a URL . 我目前在我的excel中输入了一个APIAPI可从URL下载股票价格。 Column A2:A194 is the company name, B2:B194 are the corresponding stock prices. A2:A194是公司名称,列B2:B194是相应的股票价格。

I want to create a macro which runs every 5 minutes, fetches new prices and pastes them into the adjacent column. 我想创建一个每5分钟运行一次的macro ,获取新价格并将其粘贴到相邻的列中。

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 . 该宏从上一列而不是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. 例如:在1小时结束时,我希望14列有数据:原始的2 + 12列,每5分钟获取一次价格。

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. 这是因为您使用的是Offset而不是声明要专门使用的列。 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. 您还可以很快地在后台看到所有正在进行的事情,看起来很可疑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM