Обновление листа excel vba

каролинка

0 / 0 / 0

Регистрация: 28.10.2012

Сообщений: 152

1

Как обновить листы автоматически при их модификации

01.11.2012, 13:48. Показов 11057. Ответов 4

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Всем привет!
Как можно обновить лист в экселе? я просто на одном листе вношу изменения, и мне приходится на другом ctrl+alt+l нажимать, чтоб обновлялось (
Пробовала

Visual Basic
1
 Application.Volatile True

но не уверена, что обновляется то, что нужно



0



Казанский

15136 / 6410 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

01.11.2012, 15:21

2

Visual Basic
1
ДругойЛист.Calculate

?



1



каролинка

0 / 0 / 0

Регистрация: 28.10.2012

Сообщений: 152

01.11.2012, 17:02

 [ТС]

3

Казанский, не пересчитывает(

Visual Basic
1
ThisWorkbook.Worksheets("UREN TABEL").Columns("A:AL").Calculate



0



SlavaRus

1121 / 229 / 36

Регистрация: 15.03.2010

Сообщений: 698

01.11.2012, 17:20

4

В листе случаем не автофильтр? Если да, то попробуй:

Visual Basic
1
    Worksheets("SheetName").AutoFilter.ApplyFilter



1



0 / 0 / 0

Регистрация: 28.10.2012

Сообщений: 152

01.11.2012, 17:27

 [ТС]

5

SlavaRus, оказалось что да) все работает, спасибо!)

Добавлено через 41 секунду
SlavaRus, там просто таблицы не мои, плохо понимаю что там и как организовано (((



0



How do you get spreadsheet data in Excel to recalculate itself from within VBA, without the kluge of just changing a cell value?

braX's user avatar

braX

11.5k5 gold badges20 silver badges33 bronze badges

asked Sep 30, 2008 at 18:54

Lance Roberts's user avatar

Lance RobertsLance Roberts

22.2k32 gold badges112 silver badges129 bronze badges

The following lines will do the trick:

ActiveSheet.EnableCalculation = False  
ActiveSheet.EnableCalculation = True  

Edit: The .Calculate() method will not work for all functions. I tested it on a sheet with add-in array functions. The production sheet I’m using is complex enough that I don’t want to test the .CalculateFull() method, but it may work.

MarredCheese's user avatar

MarredCheese

16.6k8 gold badges90 silver badges87 bronze badges

answered Sep 30, 2008 at 18:54

Lance Roberts's user avatar

Lance RobertsLance Roberts

22.2k32 gold badges112 silver badges129 bronze badges

4

This should do the trick…

'recalculate all open workbooks
Application.Calculate

'recalculate a specific worksheet
Worksheets(1).Calculate

' recalculate a specific range
Worksheets(1).Columns(1).Calculate

answered Sep 30, 2008 at 19:26

Graham's user avatar

1

Sometimes Excel will hiccup and needs a kick-start to reapply an equation. This happens in some cases when you are using custom formulas.

Make sure that you have the following script

ActiveSheet.EnableCalculation = True

Reapply the equation of choice.

Cells(RowA,ColB).Formula = Cells(RowA,ColB).Formula

This can then be looped as needed.

answered Sep 4, 2013 at 19:11

kambeeks's user avatar

kambeekskambeeks

811 silver badge2 bronze badges

You might also try

Application.CalculateFull

or

Application.CalculateFullRebuild

if you don’t mind rebuilding all open workbooks, rather than just the active worksheet. (CalculateFullRebuild rebuilds dependencies as well.)

answered Sep 30, 2008 at 19:52

Dave DuPlantis's user avatar

Dave DuPlantisDave DuPlantis

6,3543 gold badges27 silver badges30 bronze badges

I had an issue with turning off a background image (a DRAFT watermark) in VBA. My change wasn’t showing up (which was performed with the Sheets(1).PageSetup.CenterHeader = "" method) — so I needed a way to refresh. The ActiveSheet.EnableCalculation approach partly did the trick, but didn’t cover unused cells.

In the end I found what I needed with a one liner that made the image vanish when it was no longer set :-

Application.ScreenUpdating = True

answered Dec 2, 2014 at 17:28

AjV Jsy's user avatar

AjV JsyAjV Jsy

5,6994 gold badges34 silver badges30 bronze badges

After a data connection update, some UDF’s were not executing. Using a subroutine, I was trying to recalcuate a single column with:

Sheets("mysheet").Columns("D").Calculate

But above statement had no effect. None of above solutions helped, except kambeeks suggestion to replace formulas worked and was fast if manual recalc turned on during update. Below code solved my problem, even if not exactly responsible to OP «kluge» comment, it provided a fast/reliable solution to force recalculation of user-specified cells.

Application.Calculation = xlManual
DoEvents
For Each mycell In Sheets("mysheet").Range("D9:D750").Cells
    mycell.Formula = mycell.Formula
Next
DoEvents
Application.Calculation = xlAutomatic

answered Jun 24, 2019 at 22:28

pghcpa's user avatar

pghcpapghcpa

83311 silver badges25 bronze badges

0

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

Автоматическое обновление листа с данными

foxrm

Дата: Понедельник, 23.09.2013, 20:18 |
Сообщение № 1

Группа: Пользователи

Ранг: Прохожий

Сообщений: 6


Репутация:

0

±

Замечаний:
0% ±


Excel 2010

Здравствуйте!
Подскажите пожалуйста как можно автоматически обновить лист при поступлении новых данных
и в чем у меня возможная ошибка. Описание на скриншоте.

Скрин

Сам код, не знаю в чем ошибка. Спец. я довольно слабый пока.

[vba]

Код

Private Sub Worksheet_Change(ByVal Target As Range)

Dim i As Integer, j As Integer
  ‘Application.Calculate
‘If Not Intersect(Target, Range(«C2:C21»)) Is Nothing Then
         ‘Application.EnableEvents = False

                       For j = 1 To Cells(2, 12).Value
           For i = 1 To 20

               If Cells(1 + j, 6).Value = Cells(1 + i, 2).Value Then
   If Cells(1 + i, 1).Value <> 0 Then
  Cells(1 + j, 5).Value = Cells(1 + j, 5).Value + Cells(1 + i, 1).Value
  Cells(1 + i, 1).Value = 0
  End If
  End If
  Next
  Next
        ‘Application.EnableEvents = True
    ‘End If

               ‘ If Not Intersect(Target, Range(«A2:A21»)) Is Nothing Then
    ‘    Application.EnableEvents = False
           For i = 1 To 20
           For j = 1 To Cells(2, 12).Value
   If Cells(1 + j, 6).Value = Cells(1 + i, 2).Value Then
   If Cells(1 + i, 3).Value <> 0 Then
  Cells(1 + j, 7).Value = Cells(1 + j, 7).Value + Cells(1 + i, 3).Value
  Cells(1 + i, 3).Value = 0
  End If
  End If
  Next
  Next
    ‘Application.EnableEvents = True
    ‘End If
End Sub

[/vba]

И сам файл.

К сообщению приложен файл:

quik.xls
(69.5 Kb)

 

Ответить

nilem

Дата: Понедельник, 23.09.2013, 20:49 |
Сообщение № 2

Группа: Авторы

Ранг: Старожил

Сообщений: 1612


Репутация:

563

±

Замечаний:
0% ±


Excel 2013, 2016

У Вас в столбце Страйк числа с 12-13 знаками после запятой, а в столбце Цена — с 2 знаками. Похоже, их никак не сравнить.
Страйк можно округлить до 2-х знаков?


Яндекс.Деньги 4100159601573

 

Ответить

foxrm

Дата: Понедельник, 23.09.2013, 21:28 |
Сообщение № 3

Группа: Пользователи

Ранг: Прохожий

Сообщений: 6


Репутация:

0

±

Замечаний:
0% ±


Excel 2010

Да, конечно можно. Это одни и те же числа.

 

Ответить

nilem

Дата: Понедельник, 23.09.2013, 22:30 |
Сообщение № 4

Группа: Авторы

Ранг: Старожил

Сообщений: 1612


Репутация:

563

±

Замечаний:
0% ±


Excel 2013, 2016

У вас данные обновляются сразу во всем диапазоне А2:С21 или по одной ячейке из этого диапазона?


Яндекс.Деньги 4100159601573

 

Ответить

foxrm

Дата: Понедельник, 23.09.2013, 22:49 |
Сообщение № 5

Группа: Пользователи

Ранг: Прохожий

Сообщений: 6


Репутация:

0

±

Замечаний:
0% ±


Excel 2010

По одной или иногда по нескольким ячейкам А2:A21 B2:B21 C2:C21.
Продажа Цена Покупка. Обновление идет ежесекундное из программы Quik Junior.

 

Ответить

nilem

Дата: Вторник, 24.09.2013, 08:45 |
Сообщение № 6

Группа: Авторы

Ранг: Старожил

Сообщений: 1612


Репутация:

563

±

Замечаний:
0% ±


Excel 2013, 2016

вот так попробуйте
[vba]

Код

Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range(«A2:C21»)) Is Nothing Then Exit Sub
Dim j As Long, r As Range: Application.EnableEvents = False
With Columns(6)
     For Each r In Target.Cells
         j = r.Column
         If j <> 2 Then
             With .Find(Cells(r.Row, 2), lookat:=xlWhole)(1, IIf(j = 1, 0, 2))
                 .Value = .Value + r
             End With
         End If
     Next
End With
Application.EnableEvents = True
End Sub

[/vba]

К сообщению приложен файл:

_quik.xls
(59.5 Kb)


Яндекс.Деньги 4100159601573

 

Ответить

foxrm

Дата: Вторник, 24.09.2013, 10:21 |
Сообщение № 7

Группа: Пользователи

Ранг: Прохожий

Сообщений: 6


Репутация:

0

±

Замечаний:
0% ±


Excel 2010

Вопрос снят. Огромное, человеческое Вам спасибо nilem!

 

Ответить

nilem

Дата: Вторник, 24.09.2013, 11:50 |
Сообщение № 8

Группа: Авторы

Ранг: Старожил

Сообщений: 1612


Репутация:

563

±

Замечаний:
0% ±


Excel 2013, 2016

На здоровье :)
на других форумах не забудьте отписаться.


Яндекс.Деньги 4100159601573

 

Ответить

foxrm

Дата: Вторник, 24.09.2013, 16:29 |
Сообщение № 9

Группа: Пользователи

Ранг: Прохожий

Сообщений: 6


Репутация:

0

±

Замечаний:
0% ±


Excel 2010

Рано обрадовался(

Выдается сообщение об ошибке «Run time error 91». И ошибка в строчке которую выделил синим цветом на скрине.
Вот скрин:

Ссылка

К сообщению приложен файл:

5200129.jpg
(52.2 Kb)

Сообщение отредактировал foxrmВторник, 24.09.2013, 16:31

 

Ответить

nilem

Дата: Вторник, 24.09.2013, 17:01 |
Сообщение № 10

Группа: Авторы

Ранг: Старожил

Сообщений: 1612


Репутация:

563

±

Замечаний:
0% ±


Excel 2013, 2016

Это поправимо :)
Только сначала надо выяснить.
Ошибка происходит, потому что в столбце Страйк нет значения из столбца Цена.
По условиям вашей работы возможно такое несоответствие между Цена и Страйк?


Яндекс.Деньги 4100159601573

 

Ответить

KuklP

Дата: Вторник, 24.09.2013, 18:45 |
Сообщение № 11

Группа: Проверенные

Ранг: Старожил

Сообщений: 2369


Репутация:

486

±

Замечаний:
0% ±


2003-2010


Ну с НДС и мы чего-то стoим! kuklp60@gmail.com
WM Z206653985942, R334086032478, U238399322728

 

Ответить

foxrm

Дата: Среда, 25.09.2013, 13:15 |
Сообщение № 12

Группа: Пользователи

Ранг: Прохожий

Сообщений: 6


Репутация:

0

±

Замечаний:
0% ±


Excel 2010

По условиям вашей работы возможно такое несоответствие между Цена и Страйк?

Нет они должны быть одинаковы.

 

Ответить

 

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 ячейки, то требуется принудительное включение обновления экрана.

 

Юрий М

Модератор

Сообщений: 60585
Регистрация: 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

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

 

Юрий М

Модератор

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

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

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

 

Юрий М

Модератор

Сообщений: 60585
Регистрация: 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

 

Юрий М

Модератор

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

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

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

 

Юрий М

Модератор

Сообщений: 60585
Регистрация: 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

 

Юрий М

Модератор

Сообщений: 60585
Регистрация: 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

 

Юрий М

Модератор

Сообщений: 60585
Регистрация: 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}Как плохо, что я не умею читать!))) Спасибо, понял : )

 

Юрий М

Модератор

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

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

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

 

ran

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

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

 

Юрий М

Модератор

Сообщений: 60585
Регистрация: 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]

 

Юрий М

Модератор

Сообщений: 60585
Регистрация: 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}Здесь ДВЕ ячейки. А у Вас принудительный выход, если изменение более одной ячейки.

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

 

Юрий М

Модератор

Сообщений: 60585
Регистрация: 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

 

Юрий М

Модератор

Сообщений: 60585
Регистрация: 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}У меня такого не происходит — могу сразу после копирования/вставки активировать любую ячейку.

Понравилась статья? Поделить с друзьями:
  • Обновление источника данных для excel
  • Обновление значений ячейки в excel
  • Обновление для word 2016
  • Обновление для office excel
  • Обновление для microsoft excel 2010