• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Code that executes within a time frame

Hi, I recently put a code in my workbook to run whenever it opens - i.e., open a specific folder. However, I soon find out the code is only needed between 0800-1600 hour. Is there any code that checks the local machine time before executing?

I searched online and found some code about code to run on specific time - i.e., application.ontime, but it's not exactly my case. Thank you so much!
 
Something like below:
Code:
Private Sub Workbook_Open()
Dim tm As Double
tm = Time * 24
If tm >= 8 And tm <= 16 Then
       '\\ Call your code here!
End If
End Sub
 
Hi ,

Running code from an Excel workbook at a specific time is only possible if the workbook is already open before that specified time. Thus , if you want some code executed at 08:00 hrs. , you have to ensure that the workbook is opened before that.

A more robust alternative is to put the code within the Workbook_Open event procedure , and then use the Windows Task Scheduler to schedule running Excel and opening the workbook which has the code , at 08:00 hrs. or a minute before that. In that case , the code does not have to check the time at all.

Narayan
 
Some like to use Windows Task Scheduler as Narayan said. Some set the file to open as a VBS or BAT file. VBS is the better choice as you may want to work with more than one file using VBS methods.

I usually like to do as Narayan but give myself an out should I open the XLSM file and not want to run my AutoMacro which also closes the file. The key is to show a popup msgbox to allow time to abort the autorun. I also like to log the AutoRuns.
 

Attachments

  • AutoRunOnOpen.xlsm
    22.6 KB · Views: 1
I'd combine VBS with task scheduler like Kenneth mentioned. Though I tend to avoid such use of Excel & VBA where I can, and leverage other tools to perform the task.
 
Hi, I recently put a code in my workbook to run whenever it opens - i.e., open a specific folder. However, I soon find out the code is only needed between 0800-1600 hour.
Maybe I am not reading it correctly but with respect to the quoted line from OP's post #1, I inferred that he wants to verify the appropriate time window to execute the code and therefore looking for the same.

Have to wait for OP's response to see if that's what it is:confused:.
 
Something like below:
Code:
Private Sub Workbook_Open()
Dim tm As Double
tm = Time * 24
If tm >= 8 And tm <= 16 Then
       '\\ Call your code here!
End If
End Sub

Hi, shrivallabha, you are right, my team doesn't open the workbook on a regular basis, and that folder only need to open within certain hours.

So, that's the solution I am looking for, it works like a charm. Thank you so much!
 
Back
Top