【问题标题】:How to refresh Excel file every second?如何每秒刷新 Excel 文件?
【发布时间】:2015-06-11 14:31:23
【问题描述】:

我有一份从 Google Finance 中提取的股票价格列表,并放在我的 Excel 中的不同工作表中。我想知道,我可以根据 Google 金融股票价格每隔 SECOND(不是一分钟)刷新 Excel 表吗?

【问题讨论】:

  • 是的,有可能,您需要在 Excel 中搜索 VBA 代码,然后将其写入 Excel,如果您之前这样做过,请将您的代码添加到问题中并让我们清楚您的问题;)。
  • 谢谢大家,我已经找到解决办法了

标签: excel refresh seconds vba


【解决方案1】:

这可以在没有持续运行宏的情况下完成。它依赖于 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 调用用于管理计时器。 EntryPoint 代码开始工作,CodeToRun 包含要运行的实际代码。请注意,要使其重复,请在 CodeToRun 中调用 StartTimer。这允许它循环。您可以通过调用 StopTimer 或不再调用 StartTimer 来停止循环。这可以通过 CodeToRun 中的一些逻辑来完成。

我只是在 A1 中放入一个随机数,以便您可以看到它的更新。

【讨论】:

    【解决方案2】:
    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
    

    您可以让这个宏在后台运行。将其粘贴到 VBA 模块中。您可以从那里运行它,或者在工作表上放置一个按钮并使用它来触发它。当用户正在查看的任何工作表的单元格 A1 中键​​入“STOP”一词时,它就会停止运行。

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

    【讨论】:

    • 谢谢蒂姆。我找到了解决办法
    猜你喜欢
    • 1970-01-01
    • 2020-04-26
    • 1970-01-01
    • 2013-05-02
    • 2017-03-05
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多