Application ontime excel
На этом шаге мы рассмотрим основные методы этого объекта .
Перечислим наиболее часто используемые методы объекта Application .
Методы | Выполняемые действия |
---|---|
Calculate | Вызывает принудительное вычисление во всех открытых рабочих книгах. Например: |
Run | Запускает на выполнение подпрограмму или макрос. Синтаксис:
Например: Application.Run Macro:= «Расчет» — запускает макрос Расчет |
Volatile | Вызывает перевычисление функции пользователя при изменении значений параметров. Например, функция Квадрат будет автоматически пересчитывать результат на рабочем листе при изменении значения аргумента: |
Wait | Временно приостанавливает работу приложения без остановки работы других программ. Синтаксис: |
OnKey | Устанавливает выполнение специфицированной процедуры при нажатии заданной комбинации клавиш. Синтаксис:
Допустимо использование сочетания одновременно нажатых клавиш. С этой целью для перечисленных трех клавиш установлены следующие коды:
В примере процедуре Амортизация назначена комбинация клавиш «Ctrl»+»+» , а процедуре ПроцентнаяСтавка — Shift+Ctrl+» стрелка вправо » : |
OnRepeat и OnUndo | Определяет процедуру, выполняемую при выборе команды Правка | Повторить (Edit | Repeat) и Правка | Отменить (Edit | Undo) соответственно. Синтаксис:
|
OnTime | Назначает выполнение процедуры на определенное время. Синтаксис:
В следующем примере демонстрируется, как запустить процедуру Очистка на выполнение через 15 секунд от текущего времени: |
Quit | Закрывает приложение. Например:
На следующем шаге мы рассмотрим события этого объекта . Schedule a Macro with VBA Application.OnTimeThe VBA Tutorials BlogProgrammers love to make things more efficient. Pushing buttons just to make a code run is particularly annoying, especially when the code is supposed to run at the same time every time. Fortunately, Excel makes scheduled macro automation simple with the Application.OnTime method. The Application.OnTime MethodThe Application.OnTime method is part of the Application object, which means it lives inside Excel’s main application. If you’re using Intellisense, when you type Application.OnTime , you should see this: Notice there are four arguments, two of which are optional:
Scheduling the MacroThere are many ways to schedule your macros to run using the OnTime method. The most common ways are via specific times (1am, 11:45, 19:30) or a time relative to the existing time. You can also make other scheduling decisions, like scheduling a macro to run relative to a future date based on some user input. Again, the argument EarliestTime is your start time, and the scheduling mechanism will try to execute the specified macro at this time. As long as nothing prevents the called macro from running, this is synonymous with the start time. Conversely, if there is something preventing the called macro from running, LatestTime is essentially the time at which Excel stops trying to run the macro. Specific TimesIf a task must be run every day at the same time, it makes sense to apply the specific time technique. Let’s say you have to run a macro every day at 7am before you come into the office. You would execute a code snippet like this to make sure your macro runs before you even arrive: In this example, early_morning_task is the name of the macro you have to run at 7am. You could also use the TimeSerial function or the CDate function if you were grabbing your times from user-input variables: Make powerful macros with our free VBA Developer Kit There’s a lot to unpack here. To save time and become really good at VBA, make sure you get our free VBA Developer Kit below. It’s full of tips and pre-built macros to make writing VBA easier. Notice the use of CInt to ensure the value going into TimeSerial is an integer. Also, note that this setup uses 24-hour format, and you will need to account for that by explicitly forcing users to use 24-hour formats, making an educated guess (programmatically!), or by offering the option of entering AM/PM and calculating the 24-hour format of the input. Relative TimesYou can also schedule macros to run at relative times. The most common way is to schedule it relative to the current time. You would do this by using the Now function to grab the current time then adding some amount of time to it. The DateAdd function is a good option if you want to add two times together, and it plays well with the Now function. The following snippet fires off the macro nseconds from now, where nseconds is determined by the user. If you’re scheduling over longer time periods, you can change the “s” to an “m” for minutes or “h” for hours and adjust the prompt. Remember that a macro is executed line-by-line, so if the InputBox opens at 19:33:09 and the user waits 10 seconds then enters 15, the macro will fire at 19:33:34, not at 19:33:24. Specifying the MacroWhen you only have a single workbook, you can reference the macro directly by using its name. To write more robust code, you can specify the module to ensure no future changes to the workbook, like adding another module with an identically-named macro, will cause issues. In this snippet, we are running the macro_to_schedule from Module2. If the Application.OnTime line runs in Module1 and there is a macro entitled macro_to_schedule there, we must specify we want the identically-named macro from Module2 . It’s certainly allowed, but I don’t recommend naming your macros exactly the same in different modules because it can become confusing for a human. Scheduling Macros in Other WorkbooksBelieve it or not, you can extend the Application.OnTime method to other workbooks, even if they have identically-named macros. I have plenty of workbooks that have subroutines named main , for example. Keep in mind that Application.OnTime lives at the application level and schedules there, so you can run the OnTime method from one workbook and it will execute macros in another workbook as long as you properly specify the name of the other workbook. A call to a workbook named Other Workbook.xlsm with a macro named main in it will look like this: Don’t forget that Excel uses ! to separate the workbook name from the Modules and Sheets but uses . to separate the Module/Sheet from the macro. Scheduling Macros in Closed WorkbooksThis extends even further to closed workbooks. Since the scheduling happens at the application level, as long as the application is open, the scheduled macro should execute. A user can close all of the workbooks but leave the application running and it will be fine. In other words, all the workbooks can be closed but Excel must remain open for the OnTime method to operate. To call a macro in a closed workbook, you need to supply the full filepath to the workbook. Other than this, it’s exactly the same as scheduling a macro in another workbook: Important: the workbook will open and try to execute the macro. If security settings are such that the opened workbook is not trusted, the macro cannot run until someone clicks “Enable Macros”. Make sure you set the workbook to be trusted before using this method or you won’t get much automation benefit. Automation and RecursionIf you run the scheduler once, you will get a single scheduled event. However, if you need to run the macro with the scheduler to schedule it every day, you just shifted the burden from running the macro directly to running the scheduler. There are times this is useful, like when you cannot determine programmatically when you will need the macro, but you will know before the end of the day and it must be run overnight. In that case, you could run the scheduling macro before you go home only on days you need it. But if you know your macro will run every day no matter what, you can actually automate the scheduling itself. The best way to do this is write a recursive subroutine, which is a subroutine that calls itself. There are two common ways to do this: call the scheduler macro from the task macro or roll everything into one and make the scheduler macro the same as the task macro. First Method This will run task_sub every day at 5am. Notice how the task_sub macro calls the scheduler macro at the end, which queues up the next execution of the macro for the following morning. Second Method Continuity and CancelingFor Application.OnTime to work, the Excel instance in which it was run must remain open. It is possible to open more than one instance of Excel, and that may be useful if you use Excel often and habitually close the main window. If the instance is closed, all scheduled information will be lost — even if Excel is reopened. This is very important to remember. If you need to run a macro at a certain time each day even if Excel is closed, you’ll have to call the macro from a file, like a .vbs file, and schedule your macro using the Task Scheduler. There is also the possibility that a scheduled task must be canceled. This can be done by quitting the instance of Excel in which it was created, but doing this will nullify all scheduled tasks. What if you only wanted to cancel one schedule macro? To keep the Excel instance open and schedule a particular task, the exact time and name of the scheduled subroutine must be used. Then the Schedule parameter of the OnTime method should be set to the Boolean False . This code block has a scheduler macro and a cancellation macro: To cancel a scheduled task_sub macro, the user can simply run the cancel_macro routine. Notice the positional passing of parameters. If you don’t want to use blank positional arguments like here, use named arguments like this: Because exact times are important, and sometimes different users might enter different times, you will need to store these scheduled times somewhere. One obvious place is in a cell that won’t be overwritten. Another, but more involved option, is to write the time and macro name variables to a simple text file. A third, even more involved option, is to write custom properties for the workbook in which the scheduler resides. However you do it, it is a good idea to store the times somewhere or risk having to close Excel to cancel a macro you “lost.” StabilityAutomation is great, but only if the code is stable and what you expected to happen actually happens. If your application is meant to run a macro at a certain time every day and you plan to automate it with recursion, it is very important that Excel remains stable. That could mean manual garbage collection, learning about Windows and how the operating system interacts with Excel, and error trapping. In fact, error trapping is extremely important for rapid automation in VBA. If an application is designed to run every 5 minutes and there is no error trapping, you’re almost guaranteed to come back to a run-time error or useless output. This becomes particularly important when no humans are monitoring the program. Computers won’t fix themselves, so you’ll need a way to alert humans. One way to do this is to send yourself an email once an error is encountered. Don’t neglect stability and error trapping, especially in unattended automation scenarios. Alert humans to the errors. ConclusionApplication.OnTime makes scheduling macros easy, as long as Excel remains open. Since scheduling inherently involves some future time, the OnTime method can be called and your macro will run later. This makes recursion easy because the code is not executed immediately like most other VBA macros. That means automation becomes easy, and that’s the point of writing macros, right? It’s certainly one of the most prominent uses of Application.OnTime . The most important caveats are that 1. Excel, the application, cannot be closed 2. cancelation requests require the exact naming and time used to schedule the task to properly cancel the task. 3. code and macros must be stable for long-term, reliable automation 4. error trapping is not to be dismissed If you address these caveats satisfactorily, scheduling and automation in Excel using Application.OnTime can open many, many opportunities. I hope you’ll take a minute to subscribe for more VBA tips. Simply fill out the form below and we’ll share our best time-saving VBA tips. Oh, and if you have a question, post it in our VBA Q&A community. The best free VBA training on the web Over 2 million people use our VBA tutorials each year to help automate their work. Are you ready to reclaim your time, too? Grab our VBA Cheat Sheets and you’ll be writing macros like a professional. With over 180 tips and 135 macro examples, they include everything you need to know to become a great VBA programmer. This article was written by Cory Sarver, a contributing writer for The VBA Tutorials Blog. Excel VBAApplication.OnTime VBA, Schedule Excel to Run Macros at Periodic Intervals or a Specified TimeUser Rating: 5 / 5 Scheduling Excel to Run a Procedure at periodic intervals or at a specific time of day, with the OnTime Method. Automatically run macros. Excel Application.OnTime Method — Scheduling OnTime Events Use the Application.OnTime Method to run a procedure at specified intervals or at a specific time of day. Syntax: ApplicationObject .OnTime(EarliestTime, ProcedureName, LatestTime, Schedule). Using this method you can schedule to run a procedure in the future. You can either fix specific intervals, starting from now, when the procedure will run, or you can fix a specific time of day. The (Excel) Application Object represents the entire Excel application, and is the top-most object in the Excel object model. The EarliestTime and ProcedureName arguments are required to be specified while the other arguments are optional. The EarliestTime argument specifies the time when the procedure is to be run. The ProcedureName argument specifies the name of the procedure you want to be executed. With the LatestTime argument you can set the time limit for running the procedure viz. if you set the LatestTime to «EarliestTime + 20» and if meanwhile another procedure is being executed and Excel is not in ready mode within 20 seconds, this procedure will not run. Omitting the LatestTime argument will make Excel wait and run the procedure. Omitting the Schedule argument will default to True, which sets a new Ontime procedure. To cancel an existing OnTime procedure set earlier, specify False. To fix specific intervals starting from now, to run the procedure, use «Now + TimeValue(time)». To fix a specific time of day for the procedure to run, use «TimeValue(time)». See below examples on using these. Stop or Cancel a Running Procedure (using the OnTime method) If you attempt to close the workbook while a procedure is being run using Application.Ontime, Excel will re-open the workbook, and leave it open post completion of the procedure. Hence, you will need to cancel the procedure at a certain point or time. To cancel a running procedure (using the OnTime method), the precise time of its scheduled run is required. Note that if you don’t pass the time to a variable, Excel will not know which OnTime method to cancel, as Now + TimeValue(«00:00:03») is not static, but becomes static when passed to a variable. This means that the time when the procedure is to run (EarliestTime argument) should be assigned to a variable (use a Public variable to make the variable available to all Procedures in all modules) and then use it to cancel the OnTime. Example 1: This procedure uses the OnTime Method to auto increment cell value at specific time intervals, and Stops the procedure on crossing a specific cell value. The procedure should be entered in a Standard Module (select Insert>Module, in VBE code window). ‘Dim as a Public variable and it will be available to all Procedures in all modules. Sub CellValueAutoIncr1() ‘To run a procedure at a specific time, use TimeValue(time) viz. TimeValue(«20:30:00») will run a procedure at 8.30 pm. To run a procedure at specified time intervals (say, from now), use Now + TimeValue(time) viz. Now + TimeValue(«00:00:05») sets the time interval at 5 seconds, at which interval the procedure will run. ‘If you attempt to close the workbook while a procedure is being run using Application.Ontime, Excel will re-open the workbook, and leave it open post completion of the procedure. Hence, you will need to cancel the procedure at a certain point or time. ‘stop the procedure at a specified point — the procedure will stop after cell A1 value crosses 25 for the first time. If Cells(1, 1).Value > 25 Then ‘If you need to cancel an OnTime, you must provide the exact time that the event was schedule to take place. ‘Therefore, you need to store the time at which the procedure is to run in a Public variable and use that variable’s value in calls to OnTime. ‘To cancel a running procedure (using the OnTime method), the precise time of its scheduled run is required. Note that if you don’t pass the time to a variable, Excel will not know which OnTime method to cancel, as Now + TimeValue(«00:00:03») is not static, but becomes static when passed to a variable. This means that the time when the procedure is to run (EarliestTime argument) should be assigned to a variable (Public variable rTime in this example) and then use it to cancel the OnTime. ‘cancel the procedure by setting the Schedule argument to False: Application.OnTime rTime, «CellValueAutoIncr1», , False End Sub Example 2: This procedure uses the OnTime Method to auto increment cell value at specific time intervals, and Stops the procedure after it runs for a specific number of times. The procedure should be entered in a Standard Module (select Insert>Module, in VBE code window). Public eTime As Date Sub CellValueAutoIncr2() eTime = Now + TimeValue(«00:00:03») ‘stop the procedure after it runs for 5 times: If count = 5 Then Application.OnTime eTime, «CellValueAutoIncr2», , False End Sub Example 3: Start the OnTime procedure automatically when the workbook is opened; stop the OnTime procedure automatically on closing the workbook. This Application.OnTime procedure sets reminders at specific times and auto-closes workbook at a specified time. Add code (workbook procedures) to the Workbook module (ThisWorkbook): Private Sub workbook_open() ‘call SetReminder procedure: End Sub Private Sub Workbook_BeforeClose(Cancel As Boolean) On Error Resume Next End Sub The procedures to be entered in a Standard Module: Public dTime As Date Sub SetReminder() On Error Resume Next ‘Close the workbook at the specified time: If Time = TimeSerial(18, 30, 0) Then End If If Time = TimeSerial(17, 30, 0) Then Application.OnTime dTime, «OfficeClose» End If If Time = TimeSerial(13, 0, 0) Then Application.OnTime dTime, «LunchBreak» End If If Time = TimeSerial(11, 15, 0) Then Application.OnTime dTime, «CoffeeBreak» End Sub Sub CoffeeBreak() Dim obj As Object strMsg = obj.Popup(«Coffee Break Sir!», vbOKCancel) End Sub Sub LunchBreak() Dim obj As Object strMsg = obj.Popup(«Lunch Break Sir!», vbOKCancel) End Sub Sub OfficeClose() Dim obj As Object strMsg = obj.Popup(«Office Closing Sir!», vbOKCancel) End Sub Sub StopSetReminder() Application.OnTime dTime, «SetReminder», , False End Sub Sub CloseWorkBook() Application ontime excelThere may come a time when you need to run a procedure automatically at a particular time every day. ExcelEarliestTime — The time when you want this procedure to be run. This will run as soon as the current procedure has finished. This will run 10 seconds from the time this line of code it executed. Cancelling a scheduled Procedure When — The time at which the macro is to be run. Can be a string that specifies a time (for example, «4:30 pm» or «16:30»), or it can be a serial number returned by a function such as TimeValue or TimeSerial (for example, TimeValue(«2:30 pm») or TimeSerial(14, 30, 00)). You can also include the date (for example, «6/30 4:15 pm» or TimeValue(«6/30 4:15 pm»)). This will run as soon as the current procedure has finished. This will run 10 seconds from the time this line of code is executed. This example runs the macro named «Macro1» 15 seconds from the time the example is run. This example runs the macro named «Start» at 1:30 P.M. Cancelling a scheduled Procedure PowerPointThe method Application.OnTime does not exist in PowerPoint. OutlookThe method Application.OnTime does not exist in Outlook. Returning the correct time Scheduled the ProcedureImportantThe line of code to cancel a scheduled procedure will generate an error when you attempt to cancel a non existent procedure. Оценка статьи:
![]() ![]() ![]() ![]() ![]() ![]() Application ontime excel Ссылка на основную публикацию ![]() ![]() Похожие публикации
× × |
Таблица 1. Методы объекта Application