Vba excel обновить экран

My Excel tool performs a long task, and I’m trying to be kind to the user by providing a progress report in the status bar, or in some cell in the sheet, as shown below. But the screen doesn’t refresh, or stops refreshing at some point (e.g. 33%). The task eventually completes but the progress bar is useless.

What can I do to force a screen update?

For i=1 to imax ' imax is usually 30 or so
    fractionDone=cdbl(i)/cdbl(imax)
    Application.StatusBar = Format(fractionDone, "0%") & "done..."
    ' or, alternatively:
    ' statusRange.value = Format(fractionDone, "0%") & "done..."

    ' Some code.......

Next i

I’m using Excel 2003.

Community's user avatar

asked Sep 17, 2010 at 12:42

Jean-François Corbett's user avatar

Add a DoEvents function inside the loop, see below.

You may also want to ensure that the Status bar is visible to the user and reset it when your code completes.

Sub ProgressMeter()

Dim booStatusBarState As Boolean
Dim iMax As Integer
Dim i As Integer

iMax = 10000

    Application.ScreenUpdating = False
''//Turn off screen updating

    booStatusBarState = Application.DisplayStatusBar
''//Get the statusbar display setting

    Application.DisplayStatusBar = True
''//Make sure that the statusbar is visible

    For i = 1 To iMax ''// imax is usually 30 or so
        fractionDone = CDbl(i) / CDbl(iMax)
        Application.StatusBar = Format(fractionDone, "0%") & " done..."
        ''// or, alternatively:
        ''// statusRange.value = Format(fractionDone, "0%") & " done..."
        ''// Some code.......

        DoEvents
        ''//Yield Control

    Next i

    Application.DisplayStatusBar = booStatusBarState
''//Reset Status bar display setting

    Application.StatusBar = False
''//Return control of the Status bar to Excel

    Application.ScreenUpdating = True
''//Turn on screen updating

End Sub

Ben McCormack's user avatar

Ben McCormack

31.8k46 gold badges145 silver badges221 bronze badges

answered Sep 17, 2010 at 16:04

Robert Mearns's user avatar

Robert MearnsRobert Mearns

11.8k3 gold badges38 silver badges42 bronze badges

2

Text boxes in worksheets are sometimes not updated
when their text or formatting is changed, and even
the DoEvent command does not help.

As there is no command in Excel to refresh a worksheet
in the way a user form can be refreshed, it is necessary
to use a trick to force Excel to update the screen.

The following commands seem to do the trick:

- ActiveSheet.Calculate    
- ActiveWindow.SmallScroll    
- Application.WindowState = Application.WindowState

brettdj's user avatar

brettdj

54.6k16 gold badges113 silver badges176 bronze badges

answered Dec 19, 2011 at 12:37

Jan Petersen's user avatar

2

Put a call to DoEvents in the loop.

This will affect performance, so you might want to only call it on each, say, 10th iteration.
However, if you only have 30, that’s hardly an issue.

answered Sep 17, 2010 at 13:05

GSerg's user avatar

GSergGSerg

75.3k17 gold badges160 silver badges340 bronze badges

@Hubisans comment worked best for me.

ActiveWindow.SmallScroll down:=1
ActiveWindow.SmallScroll up:=1

answered Nov 27, 2019 at 17:57

FreeSoftwareServers's user avatar

1

Specifically, if you are dealing with a UserForm, then you might try the Repaint method. You might encounter an issue with DoEvents if you are using event triggers in your form. For instance, any keys pressed while a function is running will be sent by DoEvents The keyboard input will be processed before the screen is updated, so if you are changing cells on a spreadsheet by holding down one of the arrow keys on the keyboard, then the cell change event will keep firing before the main function finishes.

A UserForm will not be refreshed in some cases, because DoEvents will fire the events; however, Repaint will update the UserForm and the user will see the changes on the screen even when another event immediately follows the previous event.

In the UserForm code it is as simple as:

Me.Repaint

answered Mar 18, 2013 at 0:29

user2180598's user avatar

This worked for me:

ActiveWindow.SmallScroll down:=0

or more simply:

ActiveWindow.SmallScroll 0

answered Mar 23, 2020 at 17:50

PKanold's user avatar

I couldn’t gain yet the survey of an inherited extensive code. And exact this problem bugged me for months. Many approches with DoEnvents were not helpful.
Above answer helped. Placeing this Sub in meaningful positions in the code worked even in combination with progress bar

Sub ForceScreenUpdate()
    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.Wait Now + #12:00:01 AM#
    Application.ScreenUpdating = False
    Application.EnableEvents = False
End Sub

answered May 4, 2020 at 20:36

CH Oldie's user avatar

1

In my case: A complex Excel with a graphic simulation using shapes which move. In order to speed up, I wished to update the display only each 10th optimization step. Therefore, every 10th step, I had to switch it back on, followed by a doevents — but I ran into the problems described above. — Now, which is odd: Simply stating the screenupdating=True TWICE, it works. ??!! This is crazy.

        If counteR Mod 10 = 0 Then
            'must state this twice. WHY ??
            Application.ScreenUpdating = True
            Application.ScreenUpdating = True
            DoEvents
            Application.ScreenUpdating = False
        End If

answered Mar 4 at 16:46

Pelton's user avatar

1

This is not directly answering your question at all, but simply providing an alternative. I’ve found in the many long Excel calculations most of the time waiting is having Excel update values on the screen. If this is the case, you could insert the following code at the front of your sub:

Application.ScreenUpdating = False
Application.EnableEvents = False

and put this as the end

Application.ScreenUpdating = True
Application.EnableEvents = True

I’ve found that this often speeds up whatever code I’m working with so much that having to alert the user to the progress is unnecessary. It’s just an idea for you to try, and its effectiveness is pretty dependent on your sheet and calculations.

answered Sep 17, 2010 at 16:05

Michael's user avatar

MichaelMichael

1,6362 gold badges16 silver badges21 bronze badges

0

On a UserForm two things worked for me:

  1. I wanted a scrollbar in my form on the left. To do that, I first had to add an Arabic language to «Change administrative language» in the Language settings of Windows 10 (Settings->Time & Language->Change Administrative Language). The setting is actually for «Change the language of Non-Unicode Programs,» which I changed to Arabic (Algerian). Then in the properties of the form I set the «Right to Left» property to True. From there the form still drew a partial ghost right scrollbar at first, so I also had to add an unusual timed message box:
    Dim AckTime As Integer, InfoBox As Object
    Set InfoBox = CreateObject("WScript.Shell")
    'Set the message box to close after 10 seconds
    AckTime = 1
    Select Case InfoBox.Popup("Please wait.", AckTime, "This is your Message Box", 0)
    Case 1, -1
    End Select
  1. I tried everything to get the screen to redraw again to show the first text box in it’s proper alignment in the form, instead of partially underneath or at least immediately adjacent to the scrollbar instead of 4 pixels to the right where I wanted it. Finally I got this off another Stackoverflow post (which I now can’t find or I would credit it) that worked like a charm:
Me.Frame1.Visible = False
Me.Frame1.Visible = True

answered Apr 7, 2021 at 11:09

socrtwo's user avatar

socrtwosocrtwo

1221 silver badge12 bronze badges

In my case the problem was in trying to make one shape visible and another one invisible on a worksheet.

This is my approach to «inactivating» a button [shape] once the user has clicked it. The two shapes are the same size and in the same place, but the «inactive» version has dimmer colors, which was a good approach, but it didn’t work, because I could never get the screen to update after changing .visible = FALSE to = TRUE and vice versa.

None of the relevant tricks in this thread worked. But today I found a solution that worked for me, at this link on Reddit

Essentially you just call DoEvents twice in immediate succession after the code that makes the changes. Now why? I can’t say, but it did work.

Gass's user avatar

Gass

6,4822 gold badges33 silver badges37 bronze badges

answered Aug 4, 2021 at 12:51

Soproni's user avatar

SoproniSoproni

51 silver badge3 bronze badges

I’ve been trying to solve this Force a screen update on a Worksheet (not a userform) for many years with limited success with
doevents and scrolling etc.. This CH Oldie solutions works best with a slight mod.

I took out the Wait and reset ScreenUpdating and EnableEvents back to true.

This works office excel 2002 through to office 365

Sub Sheet1Mess(Mess1 As String)
    Sheet1.Range("A6").Value = Mess1
    ForceScreenUpdate
End Sub
Sub ForceScreenUpdate()
    Application.ScreenUpdating = True
    Application.EnableEvents = True
   ' Application.Wait Now + #12:00:01 AM#
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.ScreenUpdating = True
    Application.EnableEvents = True
End Sub

Gass's user avatar

Gass

6,4822 gold badges33 silver badges37 bronze badges

answered Aug 26, 2021 at 3:23

Rodney Sammut's user avatar

VBA Screen Updating is a property used to avoid or prevent distraction flashes while running the code and make it fast by turning off screen updating. We can turn off the screen updating by setting this property as “False.”

We often feel the Excel screen going crazy while the Macro is running. We almost get frustrated by that. But, how do we deal with these situations and make the code run faster than the usual slow thing?

Screen Updating is something we can notice while the excel macroA macro in excel is a series of instructions in the form of code that helps automate manual tasks, thereby saving time. Excel executes those instructions in a step-by-step manner on the given data. For example, it can be used to automate repetitive tasks such as summation, cell formatting, information copying, etc. thereby rapidly replacing repetitious operations with a few clicks.
read more
is running. When the task is executing, we notice our screen updating the values until the Macro finishes its assigned task. As our screen flickers or refreshes, it leads to the slowdown of the Excel program and takes a longer time than usual to complete the task.

In VBA, we have a property called “ScreenUpdating,” we set this property to FALSE to eliminate the screen updating process while the code runs.

This article will say goodbye to watching on-screen action drama while the code is running. Instead, today you will make your code run faster and quicker than your usual time.

Table of contents
  • Excel VBA Screen Updating
    • When to use Screen Updating Feature?
    • How to use Screen Updating Feature in VBA Code?
      • Example #1 – Turn Off Screen Updating
      • Example #2 –
    • Recommended Articles

VBA-Screen-Updating

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Screen Updating Property (wallstreetmojo.com)

When to use Screen Updating Feature?

Suppose you have any doubt about when to use this technique. Then, look into the below points.

  • Looping through a large number of cells.
  • Sending emails from Excel VBAWe can use VBA to automate our mailing feature in Excel to send emails to multiple users at once. To use Outlook features, we must first enable outlook scripting in VBA, and then use the application method.read more.
  • Switching between Excel workbooks.
  • Opening new workbooks.

How to use the Screen Updating Feature in VBA Code?

You can download this VBA ScreenUpdating Excel Template here – VBA ScreenUpdating Excel Template

Example #1 – Turn Off Screen Updating

Look at the below code.

Code:

Sub Screen_Updating()

 Dim RowCount As Long
 Dim ColumnCount As Long
 Dim MyNumber As Long

 MyNumber = 0

 For RowCount = 1 To 50

 For ColumnCount = 1 To 50
   MyNumber = MyNumber + 1
   Cells(RowCount, ColumnCount).Select
   Cells(RowCount, ColumnCount).Value = MyNumber
 Next ColumnCount

 Next RowCount

End Sub

The above has a nested VBA loopA VBA loop in excel is an instruction to run a code or repeat an action multiple times.read more to insert serial numbers from the first column to the 50th column and again to insert serial numbers starting from 51 from the second row to the 50th column.

VBA Screen Update Example 1

Like this, it will insert until it reaches the 50th row.

While this code is running, you can notice your screen flickering. You cannot do anything apart from watching this crazy moment.

To avoid all of these, we can add Screen Updating to FALSE.

To access the Screen Updating feature, first, we need to access the Application object.

VBA Screen Update Example 1-1

As we can see with the Application object, we have many properties and methods. So, select “Screen Updating” from the IntelliSense list.

Note: You must apply the Screen Updating feature immediately after declaring the variables.

Example 1-2

After selecting the Screen Updating property, put an equal sign (=).

Example 1-3

As we can see, there are two Boolean values: FALSE and TRUE.

To stop screen updating, set the status to FALSE.

Example 1-4

As the Macro starts running first, it will update the screen, updating the status to FALSE, and proceed to the next line.

Since Macro executed Screen Updating to FALSE, it will not allow the screen to update while the code is executing its task.

Example #2 –

Always Set Screen Updating to TRUE at the End

We have seen many people set the Screen Updating to FALSE but forgot to set it back to TRUE at the end of the Macro.

Always set the Screen Updating back to TRUE at the end of the Macro.

Code:

Sub Screen_Updating()

 Dim RowCount As Long
 Dim ColumnCount As Long
 Dim MyNumber As Long

 Application.ScreenUpdating = False
 MyNumber = 0

 For RowCount = 1 To 50

 For ColumnCount = 1 To 50
   MyNumber = MyNumber + 1
   Cells(RowCount, ColumnCount).Select
   Cells(RowCount, ColumnCount).Value = MyNumber
 Next ColumnCount

 Next RowCount
 Application.ScreenUpdating = True

End Sub

Recommended Articles

This article has been a guide to VBA Screen Updating. Here, we discuss how to use the Application.ScreenUpdating feature to make code run faster and quicker than your usual time, along with examples and a downloadable Excel template. Below are some useful Excel articles related to VBA: –

  • Solver Function in VBA
  • Use VBA Debug Print
  • Break For Loop in VBA
  • ThisWorkbook Property in VBA
  • VBA FreeFile
 

ran

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

Приветствую!  
Помогите разобраться с непонятным  
Private Sub Worksheet_Change(ByVal Target As Range)  
   Application.ScreenUpdating = False  
   If Target.Count > 1 Then Exit Sub  
   If Not Intersect(Target, Range(«A1»)) Is Nothing Then Exit Sub  
End Sub  
Если изменить А1, то все продолжает работать, а если скопировать и вставить 2 ячейки, то требуется принудительное включение обновления экрана.

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

А всё потому, что строка Application.ScreenUpdating = False срабатывает до принудительного выхода из процедуры (Then Exit Sub). А где включение?

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

А что непонятного? Вы обновление отключаете, а обратно не включаете. Я не раз писал уже, что лучше возвращать занчения изменных параметров и свойств.  

  Private Sub Worksheet_Change(ByVal Target As Range)  
If Target.Count > 1 Then Exit Sub  
If Not Intersect(Target, Range(«A1»)) Is Nothing Then Exit Sub  
Application.ScreenUpdating = False  
‘здесь код  
Application.ScreenUpdating = 1  
End Sub

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

ran

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

А нигде!  
В том и вопрос — почему в одном случае продолжает работать, а во втором — нет!?

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

А мне ещё вот это непонятно:  
If Not Intersect(Target, Range(«A1»)) Is Nothing Then Exit Sub  
При изменении в ячейке А1 НИЧЕГО не произойдёт. Кроме выхода из процедуры, конечно.

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

{quote}{login=RAN}{date=03.12.2011 04:01}{thema=}{post}почему в одном случае продолжает работать, а во втором — нет!?{/post}{/quote}Смотрите:    
Вы отключили обновление:  
Application.ScreenUpdating = False  
принудительно вышли, если более одной ячейки:  
If Target.Count > 1 Then Exit Sub  
а обновление не включили.

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

{quote}{login=RAN}{date=03.12.2011 03:44}{thema=Обновление экрана}{post}а если скопировать и вставить 2 ячейки, то требуется принудительное включение обновления экрана.{/post}{/quote}Вопрос на засыпку: что делает эта строка?  
If Target.Count > 1 Then Exit Sub  

  Для общего понимания: если Вы вышли из процедуры, завершая её логически, т.е. дойдя до End Sub, то VBA сам возвращает значение Application.ScreenUpdating в True. Если же Вы принудительно завершили процедуру — то…короче ничего никуда не возвращается.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

ran

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

Но ведь здесь в обоих случаях принудительное завершение процедуры!  
Я специально удалил весь код, оставив только строки принудительного выхода.  
Если выходить по строке  
If Not Intersect(Target, Range(«A1»)) Is Nothing Then Exit Sub  
то Application.ScreenUpdating возвращается в True, а если по строке  
If Target.Count > 1 Then Exit Sub  
то нет.  
Вопрос возник в процессе разбирательства с кодом, превая строка которого  
Application.ScreenUpdating = False  
последняя  
Application.ScreenUpdating = True  
а внутри кода — прерывания.

 

nerv

Пользователь

Сообщений: 3071
Регистрация: 22.12.2012

Всем добрый день)  
Объясните мне, пожалуйста, зачем включать обновление экрана : )  
Запустите два раза.  

  Sub io()  
With Application  
   MsgBox .ScreenUpdating ‘ читаем  
   .ScreenUpdating = False ‘ изменяем  
   MsgBox .ScreenUpdating ‘ читаем  
End With  
End Sub

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Запустил — и что? Переключается.

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

{quote}{login=RAN}{date=03.12.2011 04:34}{thema=}{post}  
Вопрос возник в процессе разбирательства с кодом, превая строка которого  
Application.ScreenUpdating = False  
последняя  
Application.ScreenUpdating = True  
а внутри кода — прерывания.{/post}{/quote}А где в Вашем примере Application.ScreenUpdating = True?

 

nerv

Пользователь

Сообщений: 3071
Регистрация: 22.12.2012

>Запустите два раза.  

  Первый запуск (макроса):  
True ‘ проверяем  
‘ отключаем <—  
False ‘ да, отключено  

  Второй  
True ‘ проверяем. Включено. А ведь мы его отключали)  
False

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

{quote}{login=nerv}{date=03.12.2011 04:45}{thema=}{post}А ведь мы его отключали)  
False{/post}{/quote}А теперь читаем Димин пост от 03.12.2011, 16:14

 

ran

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

Да нет его!  
Я знаю, что надо вставлять включение.  
Но меня интересует не это, а именно тот вопрос, который я задал!  

  Может конечно это мой локальный глюк, но у меня после выхода по строке  
If Target.Count > 1 Then Exit Sub  
возможность попасть на любой лист Excel появляется только после выполнения  
Application.ScreenUpdating = True

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

{quote}{login=RAN}{date=03.12.2011 04:51}{thema=}{post}возможность попасть на любой лист Excel появляется только после выполнения Application.ScreenUpdating = True{/post}{/quote}Покажите файл ТОЛЬКО с этим фрагментом.

 

Пытливый

Пользователь

Сообщений: 4587
Регистрация: 22.12.2012

Ну так The_Prist так и написал:  
Если процедура завершается «естественным путем» через End Sub, то обновление включается автоматом.  
Если «неестественным» — через Exit Sub автоматического включения обновления не происходит.

Кому решение нужно — тот пример и рисует.

 

nerv

Пользователь

Сообщений: 3071
Регистрация: 22.12.2012

{quote}{login=Юрий М}{date=03.12.2011 04:50}{thema=Re: }{post}{quote}{login=nerv}{date=03.12.2011 04:45}{thema=}{post}А ведь мы его отключали)  
False{/post}{/quote}А теперь читаем Димин пост от 03.12.2011, 16:14{/post}{/quote}Как плохо, что я не умею читать!))) Спасибо, понял : )

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

{quote}{login=Пытливый}{date=03.12.2011 04:54}{thema=}{post}Ну так The_Prist так и написал{/post}{/quote}Мало ли что написал, Главное — прочитать :-) А у Саши утро.

 

ran

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Что нужно выполнить, чтобы «сломалось»?

 

nerv

Пользователь

Сообщений: 3071
Регистрация: 22.12.2012

Пытливый, Юрий, а теперь скажите мне почему здесь результат тот же самый)  
Не утро, просто с одного языка на другой пока еще туго переключаюсь) Параллельно на js сижу мастерю : )  

  Sub io()  
With Application  
   Debug.Print .ScreenUpdating  
   .ScreenUpdating = False  
   Exit Sub  
End With  
End Sub

 

ran

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

Скопировать и вставить [b5:b6]

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

{quote}{login=RAN}{date=03.12.2011 05:03}{thema=}{post}Скопировать и вставить [b5:b6]{/post}{/quote}Скопировал, вставил — что дальше?

 

ran

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

Юрий М  
А что произошло?  
Просто выход? Есть возможность попасть на лист? У меня — нет.

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

{quote}{login=RAN}{date=03.12.2011 05:03}{thema=}{post}Скопировать и вставить [b5:b6]{/post}{/quote}Здесь ДВЕ ячейки. А у Вас принудительный выход, если изменение более одной ячейки.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

{quote}{login=RAN}{date=03.12.2011 05:10}{thema=Re: }{post} Есть возможность попасть на лист? У меня — нет.{/post}{/quote}Не очень понимаю вопрос — я ведь и так на листе это делаю. Куда ещё попасть? :-)

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

{quote}{login=nerv}{date=03.12.2011 05:00}{thema=Re: }{post}Пытливый, Юрий, а теперь скажите мне почему здесь результат тот же самый){/post}{/quote}  
Потому что это не событийная процедура.  
Sub io()  
   With Application  
       MsgBox .ScreenUpdating  
       .ScreenUpdating = False  
       MsgBox .ScreenUpdating  
       Exit Sub  
   End With  
End Sub  

  Выполняя напрямую из редактора VBA вы не отключаете обновление — иначе не смогли бы видеть ход выполнения. А вот с листа — да, отключается.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

ran

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

Давайте попробую еще раз объяснить.  
Добавляю в код первой строкой  
MsgBox Application.ScreenUpdating  
Сколько я бы ни менял значение в [A1], получаю MsgBox True, не смотря на принудительный выход.
Но стоит мне скопировать 2 ячейки — можно мышем по листу щелкать до посинения, ничего не происходит (в ячейку попасть не могу, курсор — стрелка) до того, как в VBA выполню  
Application.ScreenUpdating = True

 

nerv

Пользователь

Сообщений: 3071
Регистрация: 22.12.2012

Дмитрий, спасибо за участие) Но если честно, то я не понял : )  
Правильно ли я понимаю, что в коде ниже оно должно отключаться и не включаться?  
Если нет, то, пожалуйста, приведите пример когда, когда оно не включается)  

  Private Sub Worksheet_SelectionChange(ByVal Target As Range)  
With Application  
   Debug.Print .ScreenUpdating ‘ всегда True  
   .ScreenUpdating = False  
   Exit Sub  
End With  
End Sub

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

#30

03.12.2011 17:49:54

{quote}{login=RAN}{date=03.12.2011 05:25}{thema=}{post}стоит мне скопировать 2 ячейки — можно мышем по листу щелкать до посинения, ничего не происходит (в ячейку попасть не могу, курсор — стрелка) до того, как в VBA выполню  
Application.ScreenUpdating = True{/post}{/quote}У меня такого не происходит — могу сразу после копирования/вставки активировать любую ячейку.

VBA ScreenUpdating

Excel VBA ScreenUpdating

When we run any VBA macro with a huge set of code, the code completes but in the background we get processing data in the form of running or waiting for the pointer. And once it is done, we can only see the output. The regular way is not the proper way to see how the values are updating by running code. For example, let’s say we have written the code to generate some numbers in 100 cells. Now that code could simply generate the output without showing how the numbers are getting printed. To resolve this, we have VBA ScreenUpdating. ScreenUpdating in VBA helps us the see how the code is generating the output. This could be numbers, text, alphabets or combination. Once we run the code loop, by VBA ScreenUpdating we could able to see the numbers getting generated.

How to Use ScreenUpdating Application in Excel VBA?

We will learn how to use the ScreenUpdating application in Excel by using the VBA Code.

You can download this VBA ScreenUpdating Excel Template here – VBA ScreenUpdating Excel Template

VBA ScreenUpdating can be noticed while we run the code or macro. While the code is running, we will be able to see how our screen is getting updated by the values generated by written code in VBA. Instead of seeing the older waiting sign, by the help of VBA ScreenUpdating we can see how the screen is updating the values of output by VBA ScreenUpdating. Now by that, we can also see the name of the article itself defines it work, VBA ScreenUpdating.

VBA ScreenUpdating – Example #1

In this example, we will see a simple code for updating the screen. For this, we need some cells with numbers, as shown below. For this, follow the below steps:

VBA ScreenUpdating Example

Step 1: Open a Module from the Insert menu tab as shown below.

Insert Module 1-1

Step 2: Now write the subprocedure in the name of VBA ScreenUpdating as shown below.

Code:

Sub Screen_Update1()

End Sub

VBA ScreenUpdating Example 1-2

Step 3: We will now copy the numbers from cell A1: A3 to any other cells. Let’s say that cell be C1: C3 with the help of the below code.

Code:

Sub Screen_Update1()

Range("A1").Copy Range("C1")
Range("A2").Copy Range("C2")
Range("A3").Copy Range("C3")

End Sub

VBA ScreenUpdating Example 1-3

Step 4: Now if we run this code, we could only get the output which is copied values from column A to C. Now we will use ScreenUpdating application as shown below.

Code:

Sub Screen_Update1()

Application.ScreenUpdating
Range("A1").Copy Range("C1")
Range("A2").Copy Range("C2")
Range("A3").Copy Range("C3")

End Sub

Screen Updating Example 1-4

Step 5: We put an equal sign to select the Boolean values which are TRUE or FALSE. We will select FALSE to stop the screenupdating.

Code: 

Sub Screen_Update1()

Application.ScreenUpdating = False
Range("A1").Copy Range("C1")
Range("A2").Copy Range("C2")
Range("A3").Copy Range("C3")

End Sub

VBA ScreenUpdating Example 1-4png

Step 6: Run the code by pressing the F5 key or by clicking on the Play Button located below the menu ribbon. We will see the values are copied from column A to C.

VBA ScreenUpdating Example 1-5

This could be seen more clearly if we have a huge set of numbers.

VBA ScreenUpdating – Example #2

Let’s see another example for ScreenUpdating. This time let’s consider the number from 1 to 20 from cell A1 to A20 as shown below.

VBA ScreenUpdating Example 2-5

For using screenupdating application, follow the below steps:

Step 1: Write the subprocedure of VBA Screenupdating as shown below.

Code:

Sub Screen_Update2()

End Sub

VBA Screen Updating Example 2-1

Step 2: Now write the code to select the range cell from A1 to A20 and copy them at B1 to F20 as shown below. In a similar fashion as we saw in example-1.

Code:

Sub Screen_Update2()

Range("A1:A20").Copy Range("B1:F20")

End Sub

Range Cell Example 2-2

Step 3: To apply the screenupdating application, we will again use a similar line of code which we have seen in example-1.

Code:

Sub Screen_Update2()

Application.ScreenUpdating = False
Range("A1:A20").Copy Range("B1:F20")

End Sub

Application Example 2-3

The above-used application ScreenUpdating as FALSE will allow us to see how the VBA code updates the screen. As we have more numbers so there are chances we can see screenupdating.

Step 4: Run the code by pressing the F5 key or by clicking on the Play Button. We could see the value getting updated.

VBA ScreenUpdating Example 2-4

VBA ScreenUpdating – Example #3

There is another way to see the screen getting updated. This could be done with the help of the For-Next Loop. In this example, we will print the numbers in a Row and Column combo matrix. For this, follow the below steps:

Step 1: Write the subprocedure of VBA ScreenUpdating.

Code:

Sub Screen_Updating3()

End Sub

VBA ScreenUpdating Example 3-1

Step 2: Now declare the 2 variables for Row and Columns separately as data type Long.

Code:

Sub Screen_Updating3()

Dim RowCount As Long
Dim ColumnCount As Long

End Sub

VBA ScreenUpdating Example 3-2

Step 3: Now declare another variable which we will use as a reference to start the numbers.

Code:

Sub Screen_Updating3()

Dim RowCount As Long
Dim ColumnCount As Long
Dim MyNumber As Long

End Sub

VBA ScreenUpdating Example 3-3

Step 4: Now give the reference number from which position we want to start the counting. Here we are giving it as 0.

Code:

Sub Screen_Updating3()

Dim RowCount As Long
Dim ColumnCount As Long
Dim MyNumber As Long
MyNumber = 0

End Sub

Reference Number Example 3-4

Step 5: Now open a For loop and give the count of the Columns and Rows which want to see updating. Let say from 1 to 50.

Code:

Sub Screen_Updating3()

Dim RowCount As Long
Dim ColumnCount As Long
Dim MyNumber As Long
MyNumber = 0
For RowCount = 1 To 50

End Sub

For loop Example 3-5

Step 6: To continue the loop give MyNumber variable +1.

Code:

Sub Screen_Updating3()

Dim RowCount As Long
Dim ColumnCount As Long
Dim MyNumber As Long
MyNumber = 0
For RowCount = 1 To 50
For ColumnCount = 1 To 50
MyNumber = MyNumber + 1

End Sub

VBA Screen Updating Example 3-6

Step 7: Now select the Row and Column variables in Cell function. And then select the values stored in them and assign them to MyNumber variable.

Code:

Sub Screen_Updating3()

Dim RowCount As Long
Dim ColumnCount As Long
Dim MyNumber As Long
MyNumber = 0
For RowCount = 1 To 50
For ColumnCount = 1 To 50
MyNumber = MyNumber + 1
Cells(RowCount, ColumnCount).Select
Cells(RowCount, ColumnCount).Value = MyNumber

End Sub

MyNumber variable Example 3-7

Step 8: Now close the Loop by Next. Include Row and Column variables which we defined and used in the For-Next loop.

Code:

Sub Screen_Updating3()

Dim RowCount As Long
Dim ColumnCount As Long
Dim MyNumber As Long
MyNumber = 0
For RowCount = 1 To 50
For ColumnCount = 1 To 50
MyNumber = MyNumber + 1
Cells(RowCount, ColumnCount).Select
Cells(RowCount, ColumnCount).Value = MyNumber
Next ColumnCount
Next RowCount

End Sub

VBA ScreenUpdating Example 3-8

Step 9: Now we haven’t inserted the Screenupdating application yet. Now insert the Screenupdating application as FALSE before the start of the loop and as TRUE at the end of the loop as shown below.

Code:

Sub Screen_Updating3()

Dim RowCount As Long
Dim ColumnCount As Long
Dim MyNumber As Long
Application.ScreenUpdating = False
MyNumber = 0
For RowCount = 1 To 50
For ColumnCount = 1 To 50
MyNumber = MyNumber + 1
Cells(RowCount, ColumnCount).Select
Cells(RowCount, ColumnCount).Value = MyNumber
Next ColumnCount
Next RowCount
Application.ScreenUpdating = True

End Sub

VBA Screen Updating Example 3-10

Now compile the complete code step by step by pressing the F8 function key and then run it if no error is found. We will see, how each cell of selected rows and columns is getting updated with the values stored in it.

Row and Column Combo Matrix Example 3-9

Pros of Excel VBA ScreenUpdating

  • It is quite helpful in seeing how the screen is getting updated with the value stored in the loop.
  • We can use Screenupdating if we want to switch between worksheets and workbooks.
  • We can use any range of numbers.

Things to Remember

  • We use the insert For-Next loop as the frame or first, we can satisfy the condition of For loop and then close it by Next.
  • VBA ScreenUpdating is quite useful and visible if we are using a huge set of numbers.
  • Once done, do save the excel file as Macro enables excel format.
  • VBA ScreenUpdating can also be used for creating a macro through which we can send emails.

Recommended Articles

This is a guide to VBA ScreenUpdating. Here we discuss how to use ScreenUpdating application in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA IF Statements
  2. VBA Sort
  3. VBA While Loop
  4. VBA Environ

Home / VBA / VBA ScreenUpdating | How to Turn it ON and OFF

What is VBA Screen Updating?

ScreenUpdating is a property in VBA that you can use to turn “ON” and “OFF” the screen updating while running the code. You can turn it off before running a code that makes your code run faster and then turn it on once the execution of the code completes. You can read and write this property.

By default, screen updating is “ON” in Excel. When you normally run a code it takes a lot of flickering if that code takes time, but if you turn OFF the screen updating it will take less time than normal to run.

Turn OFF Screen Updating in VBA

  1. First, type the keyword “Application”.
  2. After that, press a dot “.” to open the properties and methods list.
  3. Now, select “ScreenUpdating”.
  4. In the end, specify “False” to it.

Once you turn off screen updating, VBA will not turn it ON once the code is executed. So it’s always better to turn it off from your end. The code would be like something below.

Points to Consider

  • Make sure to have the screen updating “ON” when you are using a user form.
  • If you are debugging code, it is better to have a screen updating “ON” so that you can see all the activities as they are.

There’s More

VBA With Statement | VBA Wait and Sleep Commands | VBA Status Bar | VBA Random Number | Line Break in a VBA Code | VBA Immediate Window (Debug.Print) | VBA Concatenate | VBA Module | VBA Random Number

Понравилась статья? Поделить с друзьями:
  • Vba excel обновить форму
  • Vba excel обновить все сводные таблицы
  • Vba excel обновить все данные
  • Vba excel область ячеек
  • Vba excel нумерация строк кода