How to refresh Excel file every second? - excel

I have a list of stock prices pulled from Google finance and placed in different sheets in my Excel. I'm wondering, Can I refresh Excel sheet every SECOND (not minute) according to the Google finance stock price?

This can be done without having a macro constantly running. It relies on the Application.OnTime method which allows an action to be scheduled out in the future. I have used this approach to force Excel to refresh data from external sources.
The code below is based nearly exclusively on the code at this link: http://www.cpearson.com/excel/ontime.aspx
The reference for Application.OnTime is at: 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
In this code, the StartTimer and StopTimer calls are used to manage the Timers. The EntryPoint code gets things started and CodeToRun includes the actual code to run. Note that to make it repeat, you call StartTimer within CodeToRun. This allows it to loop. You can stop the loop by calling the StopTimer or simply not calling StartTimer again. This can be done with some logic in CodeToRun.
I am simply putting a random number in A1 so that you can see it update.

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
You could have this macro running in the background. Paste it into a VBA module. You can run it from there or else put a button on the sheet and use that to trigger it. It's written to stop running when the word "STOP" is typed in cell A1 of whatever sheet the user is looking at.
I'm not sure it's the greatest idea to have a macro running continuously in the background, but that was the only way I could think of.

Related

Application.OnTime doesn't wait

I have some graphs that are updated based on the value in one cell. I am trying to write a script that changes the value in this cell every second and updates the graphs in the process. However, the program does not seem to wait one second to call the procedure and rather runs everything directly. I have tried other methods such as Application.wait which works in regards to waiting but it does not update the graphs. From information I have found on the internet, it seems like Application.OnTime is the best option. Could someone help me figure out why Application.OnTime does not wait one second? Here is my code:
Sub graphOverTime()
Do While Range("N5").Value = "Running"
'changes cell N5 to Not running on condition
Call my_procedure
'Update value in D3 that impacts the graphs
current_month = Range("D3").Value
Range("D3").Value =
Application.WorksheetFunction.EoMonth(current_month, 1)
DoEvents
'Wait one second to rerun procedure
Application.OnTime Now + TimeValue("0:00:01"), "graphOverTime"
Loop
End Sub
Your main problem is Do While looping which causes Application.OnTime to set overlapping scheduled calls of graphOverTime. Following is one way of doing what you wanted to in the first place
Sub graphOverTime()
If Range("N5").Value = "Running" Then
'changes cell N5 to Not running on condition
Call my_procedure
'Update value in D3 that impacts the graphs
Range("D3").Value = Application.WorksheetFunction.EoMonth(Range("D3").Value, 1)
DoEvents
'Wait one second to rerun procedure
Application.OnTime Now + TimeValue("0:00:01"), "graphOverTime", False
End If
End Sub

Workbook, Save, Close, Re-Open (w/ TimeValue),Repeat

The macro runs with a button assigned to "CloseMe". It used to run for my needs but doesn't anymore (as I tried using this code in another workbook without success). Now it saves, closes, waits 10sec to reopen, but then closes right away.
Sub CloseMe()
Application.OnTime Now + TimeValue("00:00:10"), "OpenMe"
ThisWorkbook.Close True
End Sub
Sub OpenMe()
Application.OnTime Now + TimeValue("00:10:00"), "OpenMe"
ThisWorkbook.Close True
End Sub
I need the code to save, close, wait 10sec to reopen, stay open for 10min (to collect real time data), and then repeat this process (until I interrupt it manually to stop). Thanks
The code does what you are asking it to do: a. CloseMe schedules OpenMe for 10 seconds from now and closes the workbook, then b. Excel re-opens the workbook and invokes OpenMe, which schedules itself for 10 minutes from now, then immediately proceeds to close the workbook, and finally Excel resumes at b 10 minutes later, in a loop.
My understanding is that your code has to perform something either in OpenMe or CloseMe, so you do not want to just schedule a call and close the workbook. Additionally, to cycle, one sub needs to schedule the other. In broad terms, you could go along those lines:
Sub CloseMe()
'Here, do whatever (if anything) must be done just before saving the workbook.
'...
'Schedule the OpenMe execution in 10 seconds.
'I don't understand why you need to close the workbook, but that's not the question.
Application.OnTime Now + TimeValue("00:00:10"), "OpenMe"
ThisWorkbook.Close True
End Sub
Sub OpenMe()
'Here, do whatever (if anything) must be done just as the workbook opens.
'...
'Schedule the CloseMe execution in 10 minutes.
Application.OnTime Now + TimeValue("00:10:00"), "CloseMe"
End Sub
You are calling the OpenMe sub for both Open and Close subs.
If you want this to run automatically, where does close sub get called other than the command button?
#Excelosaurus we are very close. Thanks for explaining this logically on the different subs. Here is the full code. It works but my time stamps are doubling up when it is recording, closing, & re-opening. I am capturing some RTD and in order for the RTD to refresh you need to open and close the workbook. I tried inserting in ActiveWorkbook.ForceFullCalculation = True to avoid the extra open/close subs but the RTD did not recalculate using this so the only way was to run a open/close sub.
Dim NextTime As Double
Sub RecordData()
Dim Interval As Double
Dim cel As Range, Capture As Range
Application.StatusBar = "Recording Started"
Set Capture = Worksheets("Dashboard").Range("C5:K5") 'Capture this row of data
With Worksheets("Journal") 'Record the data on this worksheet
Set cel = .Range("A2") 'First timestamp goes here
Set cel = .Cells(.Rows.Count, cel.Column).End(xlUp).Offset(1, 0)
cel.Value = Now
cel.Offset(0, 1).Resize(1, Capture.Cells.Count).Value = Capture.Value
End With
NextTime = Now + TimeValue("00:01:00")
Application.OnTime NextTime, "RecordData"
End Sub
Sub StopRecordingData()
Application.StatusBar = "Recording Stopped"
On Error Resume Next
Application.OnTime NextTime, "OpenMe", , False
On Error GoTo 0
End Sub
Sub OpenMe()
Call RecordData
Application.OnTime Now + TimeValue("00:10:00"), "CloseMe"
End Sub
Sub CloseMe()
Application.OnTime Now + TimeValue("00:00:10"), "OpenMe"
ThisWorkbook.Close True
End Sub

Excel Randbetween - Refresh without Shift-F9

I'm looking to have an excel worksheet automatically calculate a rand between function without having to hit shift f9 or calculate the workbook/worksheet.
I'm looking to do this in order to create some animated conditional formatting, but the rand between function won't update automatically even when auto calculate is turned on.
Place the following code in a standard module:
Public RunWhen As Double
Public Const cRunIntervalSeconds = 1
Public Const cRunWhat = "The_Sub"
Sub StartTimer()
RunWhen = Now + TimeSerial(0, 0, cRunIntervalSeconds)
Application.OnTime earliesttime:=RunWhen, procedure:=cRunWhat, _
schedule:=True
End Sub
Sub The_Sub()
Application.CalculateFullRebuild
StartTimer
End Sub
Sub StopTimer()
On Error Resume Next
Application.OnTime earliesttime:=RunWhen, _
procedure:=cRunWhat, schedule:=False
End Sub
This implements 1 second auto-re-calculation:
to begin, run StartTimer
to stop, run StopTimer
Adapted from Chip Pearson
So I ended up doing a VB script to automatically do something to the spreadsheet using this example:
VBA Macro On Timer style to run code every set number of seconds, i.e. 120 seconds
This basically made all of the formulas update without the user doing anything (entering data or calculating).

How to make a timer like digital watch?

I was trying to make digital watch in excel. So, when I will open a workbook then in a cell, lets say in E3 cell will show time and it will continue in every second so that it looks like a digital watch. I can do it in Access as access Form has On Timer event where I can write code to show time in a Textbox. Is there any alternative way in excel. I have tried below codes. But the codes need to click manually on Button1. Can I make it automatic to run the Button1_Click() sub in every second?
Sub Button1_Click()
Application.OnTime Now(), "RunningTime"
End Sub
Sub RunningTime()
Range("E3") = Format(Now(), "hh:mm:ss")
End Sub
I have also tried Workbook_Open() method but it runs once when I open the file.
Private Sub Workbook_Open()
Application.OnTime Now(), "RunningTime"
End Sub
There is no direct way to achieve it but you can apply some tricks to do that. First put below codes to a Module.
Public Times As Boolean
Sub TimerRun()
If Not Times Then Exit Sub
Application.OnTime Now() + TimeValue("00:00:01"), "TimerRun"
Range("E3").Value = Range("E3").Value + TimeValue("00:00:01")
End Sub
Sub TimerStop()
Times = False
End Sub
Then copy below codes and paste in Workbook_Open() event.
Private Sub Workbook_Open()
Range("E3").Value = Format(Now(), "HH:MM:SS")
Times = True
TimerRun
End Sub
If you want to make start or stop button so that you can start/stop timer manually by clicking on a button then put a form control command button and then assign TimerRun sub to start and assign TimerStop to stop timer.

Excel Macro auto-refresh workbook based on user input time

I use a lot of WEBSERVICE calls in my workbook, which is connectionless. Therefore, the only way to periodically refresh values is with a macro. To do so automatically upon workbook open and every 30 seconds thereafter, the following works great:
Dim TimeToRun
Sub auto_open()
Sheets("DataInput").Select
Sheets("DataInput").Range("A1").Activate
Application.CalculateFull
Call ScheduleWorkbookRefresh
End Sub
Sub ScheduleWorkbookRefresh()
TimeToRun = Now + TimeValue("00:00:30")
Application.OnTime TimeToRun, "WorkbookRefresh"
End Sub
Sub WorkbookRefresh()
Application.CalculateFull
Call ScheduleWorkbookRefresh
End Sub
Sub auto_close()
Application.OnTime TimeToRun, "WorkbookRefresh", , False
End Sub
As usual, users claim the refresh interval of 30 seconds is somewhere between too short and too long. So, the idea is to let users fill in the interval they want in cell B9. However, there doesn't seem to be an acceptable way to put a cell number (or variable) into the TimeValue function.
Any ideas on how I might modify the macro to allow users to choose their own refresh interval, other than making the macro available for user edit (similar to handing a loaded gun, safety off, to a troop of chimpanzees)?
Use TimeToRun = Now + TimeValue("00:00:" & Sheets("DataInput").Range("A1").Value)

Resources