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).
Related
I asked a similar question yesterday, and I got an answer but now I am having a different problem with the solution that I found.
I have some excel code, and I have it setup to autosave. And it is setup to autosave on a timer. I want to be able to have that timer reset whenever I manually save the project, but it doesn't seem to be working.
I am using the Workbook_BeforeSave command to do something (ideally reset the timer) before saving. That way if I manually save the workbook, it will start that timer over again.
I tried something like this:
Workbook:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, _
Cancel As Boolean)
Call StopTimer
End Sub
Module:
Public Sub StartTimer()
RunWhen = Now + TimeValue("00:00:10")
cRunWhat = "AutoSave"
Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat, Schedule:=True
End Sub
Public Sub StopTimer()
On Error Resume Next
Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat, Schedule:=False
End Sub
But that does not seem to work. I even tried a simplified version, where I start a timer, and then just manually run StopTimer, and it doesn't stop the timer.
Is there something that I am missing on how StopTimer() should be working?
Thanks for any help!
Edit: Solution I used
I was able to accomplish what I wanted using the following methods.
In the Workbook
I used the function Workbook_BeforeSave() in order to stop the timer after being saved.
Private Sub Workbook_BeforeSave(ByVal SaveAsUi As Boolean, _
Cancel As Boolean)
Call StopTimer
End Sub
This is calling the Module StopTimer(). Which is defined on the Module level.
Option Explicit
Public RunWhen
Public cRunWhat
Public Sub StartTimer()
RunWhen = Now + TimeValue("00:01:00")
cRunWhat = "Save"
Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat, Schedule:=True
End Sub
Public Sub StopTimer()
On Error Resume Next
Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat, Schedule:=False
StartTimer
End Sub
Now, I had a different function in the workbook calling StartTimer, and Save() was just a basic save the workbook function.
The main issue I was having was solved here. But the other post I made helped me through it a little bit as well. Linked here
The solution is copied here.
First off, check that your Module starts with the magic line Option Explicit - this means that Excel will throw an error if you haven't explicitly defined a Variable before trying to use it. Otherwise, it will treat it as a blank value by default. There is actually a tickbox under Tools / Options ("Require Variable Declaration") to automatically shove this at the top of all your modules.
Without:
Sub BadCode()
MsgBox 10 + NotAVariable
End Sub
10
With:
Option Explicit
Sub BadCode()
MsgBox 10 + NotAVariable
End Sub
Compile Error:
Variable not defined
Next, make sure that your Variables are defined at a module level, not in a Sub or Function - this means that other Subs and Functions can "see" the variable:
Without:
Sub Part1()
Dim SomeNumber AS Long
SomeNumber = 4
End Sub
Sub PartB()
MsgBox 10 + SomeNumber
End Sub
Compile Error:
Variable not defined
With:
Dim SomeNumber AS Long
Sub Part1()
SomeNumber = 4
End Sub
Sub PartB()
MsgBox 10 + SomeNumber
End Sub
14
You can use Dim SomeNumber, Public SomeNumber or Private SomeNumber - using Public will let other modules "see" the variable too, while Private will only let code in that specific module "see" it.
I had a similar issue where I was saving after the end of every line- but wanted to reset the autosave timer to x seconds in the future when I am editing multiple lines.
The Marco reports !Save function not available. Substituted with one of my SaveasXLSB Macros and it worked.
I am hoping this keeps kicking the can down the road so to speak so when the system is idle for that amount of time /then/ it saves...
Option Explicit
Public RunWhen
Public cRunWhat
Public Sub StartTimer(Optional StrTimevalue As String = "00:00:10")
RunWhen = Now + TimeValue(StrTimevalue)
cRunWhat = "SaveAsDefaultXLSB"
Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat, Schedule:=True
End Sub
Public Sub StopTimer()
On Error Resume Next
Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat, Schedule:=False
StartTimer ""
End Sub
I am using this VBA code to refresh my entire workbook at specific time intervals. (thanks to this thread)
As you can see, it is currently set to refresh every 60 minutes.
Public RunWhen As Double
Public Const cRunIntervalMinutes = 60
Public Const cRunWhat = "Workbook_RefreshAll"
Sub StartTimer()
RunWhen = Now + TimeSerial(0, cRunIntervalMinutes, 0)
Application.OnTime earliesttime:=RunWhen, procedure:=cRunWhat, _
schedule:=True
End Sub
Sub StopTimer()
On Error Resume Next
Application.OnTime earliesttime:=RunWhen, _
procedure:=cRunWhat, schedule:=False
End Sub
Sub Workbook_RefreshAll()
Application.CalculateFullRebuild
ActiveWorkbook.RefreshAll
Call StartTimer
End Sub
The code works great, however there’s one thing I wish it could also do:
Any time the sheet is opened, and/or
Any time this VBA code executes the sheet refresh process
I would like the AutoFilter to be "Cleared" (not disabled or turned off) as in the screen grab below:
AutoFilter Clear
Thanks in advance for any assistance.
Cheers
This should do the trick. You may of course do it for one Sheet only, if you wish.
Sub Workbook_RefreshAll()
Dim sh As Worksheet
Application.CalculateFullRebuild
ActiveWorkbook.RefreshAll
For Each sh In ActiveWorkbook.Worksheets
If Not (sh.AutoFilter Is Nothing) Then sh.AutoFilter.ShowAllData
Next sh
Call StartTimer
End Sub
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.
I'm using Excel 2010, and want to create a countdown timer in excel. The code will be started and stopped by using buttons with macros attached to them. The problem occurs when the "start" button is pushed. The code above is utilizing Cell "B1" as the input spot, because I was just trying to get it to work, but every time I tried, it would always say:
"Cannot run the macro . The macro may not be available in this workbook or all macros may be disabled".
Yes I enabled all macros before putting this here. I want to be able to take user input, and to make that the time that the timer starts at instead of just using cell "B1".
'Macro for Starting the timer (attached to the start button)
Sub startTimer()
Application.OnTime Now + TimeValue("00:00:01"), "nextTick"
End Sub
'Macro for next second
Sub nextTick()
Sheet1.Range("B1").Value = Sheet1.Range("B1").Value - TimeValue("00:00:01")
startTimer
End Sub
'Macro for stopping the timer (attached to the end button)
Sub stopTimer()
Application.OnTime Now - TimeValue("00:00:01"), "nextTick", , False
End Sub
I modified your code very slightly and put it in a standard module:
Public Future As Double
Sub StartTimer()
Future = Now + TimeSerial(0, 0, 1)
Application.OnTime earliestTime:=Future, procedure:="nextTime", _
schedule:=True
End Sub
Sub nextTime()
Sheet1.Range("B1").Value = Sheet1.Range("B1").Value - TimeValue("00:00:01")
StartTimer
End Sub
Sub StopTimer()
On Error Resume Next
Application.OnTime earliestTime:=Future, _
procedure:="nextTime", schedule:=False
End Sub
Both StartTimer() and StopTimer() run just fine.
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.