如何每秒刷新Excel文件?

我有一个从Google财经中提取的股票价格清单,并放在Excel中的不同表格中。 我想知道,根据Google的财务股票价格,我可以每隔两秒刷新一次Excel表格(而不是分钟)吗?

这可以在没有macros不断运行的情况下完成。 它依赖于Application.OnTime方法,该方法允许在将来调度行动。 我已经使用这种方法强制Excel从外部来源刷新数据。

下面的代码几乎完全基于此链接上的代码: http : //www.cpearson.com/excel/ontime.aspx

Application.OnTime的参考位于: https : //msdn.microsoft.com/en-us/library/office/ff196165.aspx

Dim RunWhen As Date Sub StartTimer() Dim secondsBetween As Integer secondsBetween = 1 RunWhen = Now + TimeSerial(0, 0, secondsBetween) Application.OnTime EarliestTime:=RunWhen, Procedure:="CodeToRun", Schedule:=True End Sub Sub StopTimer() On Error Resume Next Application.OnTime EarliestTime:=RunWhen, Procedure:="CodeToRun", Schedule:=False End Sub Sub EntryPoint() 'you can add other code here to determine when to start StartTimer End Sub Sub CodeToRun() 'this is the "action" part [A1] = WorksheetFunction.RandBetween(0, 100) 'be sure to call the start again if you want it to repeat StartTimer End Sub 

在此代码中,StartTimer和StopTimer调用用于pipe理定时器。 EntryPoint代码让事情开始,CodeToRun包含实际运行的代码。 请注意,为了重复,您可以在CodeToRun中调用StartTimer。 这允许它循环。 您可以通过调用StopTimer来停止循环,也可以不再调用StartTimer。 这可以通过CodeToRun中的一些逻辑完成。

我只是在A1中放一个随机数,这样你就可以看到它的更新。

 Sub RefreshFormulasEverySecond() Dim dtTargetTime As Date Debug.Print "Started" Do While Range("A1").Value <> "STOP" Application.Calculate dtTargetTime = Now + TimeValue("0:00:01") Do While Now < dtTargetTime DoEvents Loop Debug.Print Now Loop Debug.Print "Stopped" End Sub 

你可以让这个macros在后台运行。 将其粘贴到VBA模块中。 你可以从那里运行它,或者在工作表上放一个button并使用它来触发它。 当用户正在查看的单元格A1中键入单词“停止”时,它被写入停止运行。

我不确定在后台连续运行macros是最好的办法,但这是我能想到的唯一方法。