Содержание
- Событие Worksheet.Change (Excel)
- Синтаксис
- Параметры
- Возвращаемое значение
- Замечания
- Пример
- Поддержка и обратная связь
- Excel VBA
- Worksheet Change Event, Excel VBA
- Excel vba if target columns
Событие Worksheet.Change (Excel)
Происходит при изменении ячеек на листе пользователем или внешней ссылкой.
Синтаксис
expression. Изменение (целевой объект)
Выражение Переменная, представляющая объект Worksheet .
Параметры
Имя | Обязательный или необязательный | Тип данных | Описание |
---|---|---|---|
Target (Целевое значение) | Обязательный | Диапазон | Измененный диапазон. Может быть несколько ячеек. |
Возвращаемое значение
Nothing
Замечания
Это событие не возникает при изменении ячеек во время пересчета. Используйте событие Calculate для перехвата пересчета листа.
Пример
В следующем примере кода цвет измененных ячеек изменяется на синий.
В следующем примере кода проверяется, что при изменении значения ячейки измененная ячейка находится в столбце A, а также если измененное значение ячейки больше 100. Если значение больше 100, смежная ячейка в столбце B изменяется на красный цвет.
В следующем примере кода значения в диапазоне A1:A10 задаются в верхнем регистре при вводе данных в ячейку.
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Excel VBA
Worksheet Change Event, Excel VBA
User Rating: 5 / 5
Worksheet Change Event in VBA and Preventing Event Loops
Related Links:
Contents:
Worksheet_Change Event:
You can auto run a VBA code, when content of a worksheet cell changes, with the Worksheet_Change event. The change event occurs when cells on the worksheet are changed either by the user, or by any VBA application or by an external link, but not when a cell changes due to recalculation as a result from formula or due to format change. For changes made by calculation, use Worksheet_Calculate event.
Worksheet change procedure is installed with the worksheet, ie. it must be placed in the code module of the appropriate Sheet object. To create a worksheet change event: use the Visual Basic Editor -> in the Project Explorer, double click on the appropriate sheet (under ‘Microsoft Excel Objects’ which is under the VBAProject/name of your workbook) -> in the Code window, select «Worksheet» from the left-side «General» drop-down menu and then select «Change» from the right-side «Declarations» drop-down menu. You will get a procedure «shell» in the code window as follows:
Private Sub Worksheet_Change(ByVal Target As Range)
Target is a parameter of data type Range (ie. Target is a Range Object). It refers to the changed Range and can consist of one or multiple cells. If Target is in the defined Range, and its value or content changes, it will trigger the vba procedure. If Target is not in the defined Range, nothing will happen in the worksheet. In this manner, you can limit the events to a particular range for both the Change and SelectionChange events. This can be done in multiple ways:
Using Target Address. Trigger the procedure, if a single cell (A5) value is changed:
If Target.Address = «$A$5» Then MsgBox «Success»
If Target.Address = Range(«$A$5»).Address Then MsgBox «Success»
If Target.Address = Range(«A5»).Address Then MsgBox «Success»
Using Target Address. If cell (A1) or cell (A3) value is changed:
If Target.Address = «$A$1» Or Target.Address = «$A$3» Then MsgBox «Success»
Using Target Address. If any cell(s) value other than that of cell (A1) is changed:
If Target.Address <> «$A$1» Then MsgBox «Success»
The following use of Target.Address is not correct, and the code will not run:
If Target.Address = «$a$5» Then MsgBox «Success»
If Target.Address = «A1» Then MsgBox «Success»
If Target.Address = «$A$1:$A$10» Then MsgBox «Success»
If Target.Address = Range(«$A$1:$A$10») Then MsgBox «Success»
Note : Target.Address should be an absolute reference [unless used as Range(«A5»).Address — see above] and in Caps. Use this to run code when content of a single cell is changed or when any cell(s) other than a specific cell is changed.
Trigger the procedure, if any cell in a column(s) is changed, say for any change in a cell in column B or column C:
If Target.Column = 2 Or Target.Column = 3 Then MsgBox «Success»
Intersect method for a single cell. If Target intersects with the defined Range of A1 ie. if cell (A1) value is changed, the code is triggerred:
If Not Application.Intersect(Target, Range(«A1»)) Is Nothing Then MsgBox «Success»
Trigger the procedure, if at least one cell of Target is A1,B2,C3:
If Not Application.Intersect(Target, Range(«A1,B2,C3»)) Is Nothing Then MsgBox «Success»
At least one cell of Target is within the range C5:D25:
If Not Application.Intersect(Target, Me.Range(«C5:D25»)) Is Nothing Then MsgBox «Success»
If you want the code to run when only a single cell in Range(«C1:C10») is changed and do nothing if multiple cells are changed:
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range(«C1:C10»)) Is Nothing Or Target.Cells.Count > 1 Then
End Sub
Preventing Event Loops with Application.EnableEvents = False
Example of a recursive loop code:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Application.Intersect(Target, Range(«A1:A10»)) Is Nothing Then
Range(«A5»).Value = Range(«A5»).Value + 1
End Sub
Recursive Event Loop:
If, at each runtime, the worksheet_change event changes the content of a cell which itself is part of the Target Range (ie. which triggers the change event), it will result in reprocessing the change event repeatedly. Recursion is the process of repeating in a similar way viz. when the procedure calls itself. Refer to above example of a recursive loop code, if any cell content in Range(«A1:A10») is changed by the user, the cell A5 value will change and increment by 1; this will again trigger the change event [because of change in value of cell A5 which is in the Target Range(«A1:A10»)] and will in turn change the cell A5 value by incrementing it by 1; and then this change in cell A5 will again trigger the change event and change the cell A5 value by incrementing it by 1; and so on. This will result in a recursive loop which might result in a ‘Out Of Stack Space’ untrappable error, or depending on the Excel setting, the loop might terminate at a threshold limit of say 100. To prevent this, enter the following at the beginning of the code: Application.EnableEvents = False. This means that any change made by the VBA code will not trigger any event and will not enable restarting the worksheet_change event. EnableEvents is not automatically changed back to True, this should be specifically done in your code, by adding the following line at the end of the code: Application.EnableEvents = True. Meanwhile, if during runtime, your code encounters an error, you will need an ErrorHandler (to change EnableEvents back to True) because events have been disabled in the beginning of the code. This can be done as follows.
ErrorHandler, Example 1:
Private Sub Worksheet_Change(ByVal Target As Range)
‘on the occurrence of an error procedure flow is directed to the error-handling routine (ie. ErrHandler) which handles the error
On Error GoTo ErrorHandler
‘to prevent recursion — so that any change made by code will not trigger an event to restart the Worksheet_Change event
‘on changing cell A1 or B1, go to ErrorHandler which reverts EnableEvents to True & then exit sub
If Target.Address = «$A$1» Or Target.Address = «$B$1» Then GoTo ErrorHandler
‘if value of any cell in column 1 or 2 is changed
If Target.Column = 1 Or Target.Column = 2 Then
‘if changed cell value is numeric ie. new value is not text
If IsNumeric(Target) Then
‘increment cell B2 value by 1
Range(«B2»).Value = Range(«B2»).Value + 1
‘EnableEvents is not automatically changed back to True & hence this needs to be done specifically at the end of the code before exit.
‘because an exit statement (ex. Exit Sub) is not placed above, the error-handling routine will also execute when there is no error.
End Sub
ErrorHandler, Example 2:
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next ‘skip all run-time errors
If Target.Address = «$A$1» Or Target.Address = «$B$1» Then Exit Sub
If Target.Column = 1 Or Target.Column = 2 Then
If IsNumeric(Target) Then
Range(«B2»).Value = Range(«B2»).Value + 1
On Error GoTo 0 ‘Turn off error trapping and re-allow run time errors
End Sub
On Error Statements explained:
On Error Resume Next: Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred, and execution continues from that point.
The On Error GoTo 0 statement turns off error trapping. It disables enabled error handler in the current procedure and resets it to Nothing.
On Error GoTo Line: Enables the error-handling routine that starts at the specified Line. The On Error GoTo statement traps all errors, regardless of the exception class.
Источник
Excel vba if target columns
Модератор форума: китин, _Boroda_
Мир MS Excel » Вопросы и решения » Вопросы по VBA » Как определить, что была вставлена строка? (или несколько) (Макросы/Sub)
Как определить, что была вставлена строка? (или несколько)
Michael_S | Дата: Вторник, 12.04.2016, 14:49 | Сообщение № 1 | ||||||||||||||||||||||||||||||||||||||
|
Требуется помощь
Каким образом можно реализовать в Excel нижеизложенный набор действий?
Исходные данные: три столбца, A — ячейки с цифрами, B — пустые ячейки, некоторым присваивается буква в зависимости от значения С, С — текстовое слово (2 варианта).
Необходимо при введении варианта 1 в одну из ячеек С оставить все без изменений, а при введении варианта 2 в ячейку из столбца С:
— Вставить пустую строку ниже активной;
— Изменить цвет активной строки;
— Присвоить ячейке А в пустой строке значение ячейки А активной строки строки;
— Присвоить ячейке В в пустой строке определенный символ, скажем «Х»;
Я написал макросы, выполняющие данные действия при нажатии кнопки на панели, но задача стоит в постоянном сканировании/анализе всего листа/книги на предмет изменения содержимого столбца С.
13 ответов
405
18 апреля 2005 года
Dmitrii
554 / / 16.12.2004
Цитата:
Originally posted by Welder
Требуется помощь
…
задача стоит в постоянном сканировании/анализе всего листа/книги на предмет изменения содержимого столбца С.
Рекомендую воспользоваться событием «Change» рабочего листа. Вот пример макроса, который следит за изменением содержимого любой ячейки столбца C:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 3 Then
MsgBox «Изменение в столбце С»
End If
End Sub
Код надо поместить в модуль кода того листа, с которым Вы работаете.
А вот так можно проследить за изменением в конкретной ячейке:
If Target.Address = «$C$1» Then
275
18 апреля 2005 года
pashulka
985 / / 19.09.2004
Учитывая, что в вопросе не было чётко определено, в одном листе необходимо отслеживать подобные манипуляции или во всех, а также то, что полный ответ мною был написан, но уважаемый Dmitrii опубликовал свою версию раньше, добавлю, что можно использовать событие рабочей книги, а именно :
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Excel.Range)
End Sub
Примечание :
Расположить его необходимо только в модуле ThisWorkbook ЭтаКнига, а не в стандартном модуле или тем паче модуле класса.
10K
19 апреля 2005 года
Welder
8 / / 18.04.2005
Цитата:
Originally posted by pashulka
Учитывая, что в вопросе не было чётко определено, в одном листе необходимо отслеживать подобные манипуляции или во всех, а также то, что полный ответ мною был написан, но уважаемый Dmitrii опубликовал свою версию раньше, добавлю, что можно использовать событие рабочей книги, а именно :
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Excel.Range)
End Sub
Примечание :
Расположить его необходимо только в модуле ThisWorkbook ЭтаКнига, а не в стандартном модуле или тем паче модуле класса.
Может я вопрос немного некорректно задал, но вроде бы все условия описал. Стоит, наверное, указать что ячейки столбца С по умолчанию пустые и заполняются вручную
275
19 апреля 2005 года
pashulka
985 / / 19.09.2004
Дело в том, что принципиальное различие между двумя предложенными вариантами не относится напрямую к условиям задачи, а заключается в том, что Dmitrii предложил Вам использовать событие рабочего листа, а я аналогичное событие, но рабочей книги. Т.е. если Вы хотите запускать макрос в отдельно взятом рабочем листе, то безусловно стоит воспользоваться советом Dmitrii, а если во всех рабочих листах, то моим. Все промежуточные варинты надо рассматривать отдельно, исходя из каждого конкретного случая.
——————-
Именно это я имел ввиду и ничего более
так что не стоит рассматривать мой предыдущий пост как критику, так его основная задача об’яснить почему всё-таки я предложил свой вариант.
10K
19 апреля 2005 года
Welder
8 / / 18.04.2005
Цитата:
Originally posted by pashulka
Дело в том, что принципиальное различие между двумя предложенными вариантами не относится напрямую к условиям задачи, а заключается в том, что Dmitrii предложил Вам использовать событие рабочего листа, а я аналогичное событие, но рабочей книги. Т.е. если Вы хотите запускать макрос в отдельно взятом рабочем листе, то безусловно стоит воспользоваться советом Dmitrii, а если во всех рабочих листах, то моим. Все промежуточные варинты надо рассматривать отдельно, исходя из каждого конкретного случая.
——————-
Именно это я имел ввиду и ничего более
так что не стоит рассматривать мой предыдущий пост как критику, так его основная задача об’яснить почему всё-таки я предложил свой вариант.
Спасибо за консультацию. Я не специалист в VBA и программировании вообще, просто захотелось автоматизировать некоторые процессы в целях экономии времени.
А в чем разница между размещением макросов в модулях и в MS Excel Objects?
10K
19 апреля 2005 года
Welder
8 / / 18.04.2005
ByVal Target As Range
ByVal Sh As Object, ByVal Target As Excel.Range
Объясните пожалуйста синтаксис этих команд
275
19 апреля 2005 года
pashulka
985 / / 19.09.2004
Аргументы :
Sh — это рабочий лист/листы в котором произошло изменение данных в ячейках.
Target — это ячейка/диапазон ячеек где произошло изменение данных.
Примечание :
— Изменение это не только ввод новых данных, но также и удаление старых и переход в режим редактирования (даже без изменения данных)
— Обратите внимание на то, что если Target представляет собой дипазон ячеек (в том числе и об’единённых, несмежных), то свойство Value аргумента Target будет представлять собой массив значений.
P.S.
Вы размещаете событие не в MS Excel Objects, а в программном модуле, который соответствует этому об’екту.
10K
20 апреля 2005 года
Welder
8 / / 18.04.2005
Цитата:
Originally posted by pashulka
Учитывая, что в вопросе не было чётко определено, в одном листе необходимо отслеживать подобные манипуляции или во всех, а также то, что полный ответ мною был написан, но уважаемый Dmitrii опубликовал свою версию раньше, добавлю, что можно использовать событие рабочей книги, а именно :
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Excel.Range)
End Sub
Примечание :
Расположить его необходимо только в модуле ThisWorkbook ЭтаКнига, а не в стандартном модуле или тем паче модуле класса.
С контролем на изменение все понятно. А как можно реализовать контроль за введением определенного слова в ячейку, например «Да» — работает, «Нет» — без изменений?
405
20 апреля 2005 года
Dmitrii
554 / / 16.12.2004
Цитата:
Originally posted by Welder
С контролем на изменение все понятно. А как можно реализовать контроль за введением определенного слова в ячейку, например «Да» — работает, «Нет» — без изменений?
If Target.Address = «$C$1» And Target.Value = «да» Then
‘…
End If
10K
25 апреля 2005 года
Welder
8 / / 18.04.2005
Цитата:
Originally posted by Dmitrii
If Target.Address = «$C$1» And Target.Value = «да» Then
‘…
End If
Помогите, вылетает ошибка Run-time error «13»
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 15 And Target.Value = «Cut out» Then
ActiveCell.EntireRow.Insert
ActiveCell.Offset(rowOffset:=0, columnOffset:=0).Activate
numRows = Selection.Rows.Count
numColumns = Selection.Columns.Count
Selection.Resize(numRows, numColumns + 19).Select
With Selection.Interior
.ColorIndex = 3
.Pattern = xlSolid
End With
End If
End Sub
Что не так?
275
25 апреля 2005 года
pashulka
985 / / 19.09.2004
По всей видимости аргумент Target представляет собой диапазон ячеек, а это значит, что изменения затрагивают более чем одну ячейку и следовательно свойство .Value представляет собой массив значений. А значит просто использовать Target.Value уже нельзя. Вот один из вариантов решения Вашей проблемы :
Код:
Target(1).Value
Target.Item(1).Value
10K
26 апреля 2005 года
Welder
8 / / 18.04.2005
Цитата:
Originally posted by pashulka
По всей видимости аргумент Target представляет собой диапазон ячеек, а это значит, что изменения затрагивают более чем одну ячейку и следовательно свойство .Value представляет собой массив значений. А значит просто использовать Target.Value уже нельзя. Вот один из вариантов решения Вашей проблемы :
Код:
Target(1).Value
Target.Item(1).Value
Если несложно, подскажите поточнее каким образом изменить код с помощью этого варианта?
275
26 апреля 2005 года
pashulka
985 / / 19.09.2004
Код:
If Target.Column = 15 And Target.Item(1).Value = «Cut out» Then
Posted by Phil Ridley on February 03, 2002 7:23 PM
Hi all,
I have a macro where I am using an if statement to execute functions on cells in certain columns. I need to know how to phrase the multiple choice «IF» statement (if target.column = 1 or 2 or 3 ?)
any help would be appreciated.
Phil.
Posted by Tom Urtis on February 03, 2002 7:55 PM
If Target.Column < 4 Then (nt)
Posted by Phil Ridley on February 03, 2002 9:31 PM
What about target.column= 6 or 9 or 11 ?
The or statement seems only to work for the last value in the range.
Posted by Bariloche on February 03, 2002 9:58 PM
Re: What about target.column= 6 or 9 or 11 ?
Phil,
If you are doing slightly different things to the various coulmns, you might want to use a Select Case statement. Then you can list all your columns:
Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)Select Case Target.Column
Case Is = 3
MsgBox "You're in column 3"Case Is = 1, 2, 4
MsgBox "You're in column " & Target.ColumnCase Is >= 5
MsgBox "You're in column " & Target.ColumnEnd Select
End Sub
have fun
Posted by Phil Ridley on February 03, 2002 10:38 PM
Excellent. Thank you ! n/t
Case Is = 3 MsgBox «You’re in column 3» Case Is = 1, 2, 4 MsgBox «You’re in column » & Target.Column Case Is >= 5 MsgBox «You’re in column » & Target.Column End Select
: The or statement seems only to work for the last value in the range.
In this Article
- What are VBA events?
- Types of Events
- Dangers of Using Code in Events
- Disable Events
- Workbook Events Examples (not exhaustive)
- Workbook Open Event
- Workbook New Sheet Event
- Workbook Before Save Event
- Workbook Before Close Event
- Worksheet Event Examples (not exhaustive)
- Worksheet Change Event
- Worksheet Before Double Click Event
- Worksheet Activate Event
- Active X Control Events (not exhaustive)
- Command Button Click Event
- Drop Down (Combo Box) Change Event
- Tick Box (Check Box) Click Event
- UserForm Events (not exhaustive)
- UserForm Activate Event
- Change Event
- Click Event
- Chart Events
- Application Events
- Application.OnTime
- Application.OnKey
What are VBA events?
Events are happening all the time when a user opens an Excel workbook and starts doing various actions such as entering data into cells or moving between sheets
Within the Visual Basic Editor (ALT+F11), sub routines are already set up which can get fired off when the user does something e.g. entering data into a cell. The sub routine does not provide any action code, merely a ‘Sub’ statement and an ‘End Sub’ statement with no code between them. They are effectively dormant so nothing happens until you enter some code.
Here is an example based on the ‘Change’ event in a worksheet:
As a VBA programmer, you can add in code to make certain things happen when the user takes a specific action. This gives you the chance to control the user, and to prevent them taking actions that you do not want them to do and which might damage your workbook. For example, you may want them to save off their own individual copy of the workbook under another name, so that they do not affect the original, which may be being used by a number of users.
If they close the workbook, then they will automatically be prompted to save their changes. However, the workbook has a ‘BeforeClose’ event and you can enter code to prevent the workbook being closed and firing off a ‘Save’ event. You can then add a button to the worksheet itself and put your own ‘Save’ routine onto it. You can also disable the ‘Save’ routine using the ‘BeforeSave’ event
An understanding of how events work is absolutely essential to a VBA programmer.
Types of Events
Workbook Events – these events are fired off based on what the user does with the workbook itself. They include user actions such as opening the workbook, closing the workbook, saving the workbook, adding or deleting sheet
Worksheet Events – these events are fired off by a user taking actions on a specific worksheet. Every worksheet within the workbook has an individual code module, which contains various events specifically for that worksheet (not for all the worksheets). These include user actions such as changing the contents of a cell, double clicking on a cell, or right clicking on a cell.
Active X Control Events – Active X controls can be added to a worksheet using the ‘Insert’ icon on the ‘Developer’ tab in the Excel ribbon. These are often button controls to enable the user to take various actions under control of your code, but they can also be objects such as drop downs. Using Active X controls as opposed to Form controls on the worksheet gives a whole scope for programmability. Active X controls give you far more flexibility from a programming point of view over using form controls in a worksheet.
For example, you could have two drop down controls on your worksheet. You want the available list in the second drop down to be based on what the user chose in the first drop down. Using the ‘Change’ event on the first drop down, you can create code to read what the user has selected and then update the second drop down. You could also de-activate the second drop down until the user has made a selection in the first drop down
UserForm Events – You can insert and design a professional looking form to use as a pop-up. All the controls that you place on your form are Active X controls and they have the same events as the Active X controls that you might place on a worksheet
Chart Events – These events are only related to a chart sheet and not to a chart appearing as part of a worksheet. These events include resizing the chart or selecting the chart.
Application Events – These use the Application object in VBA. Examples would allow code to be fired off when a certain key is pressed or when a certain time is reached. You could program a situation where the workbook is left open 24/7 and it imports data from an external source overnight at a pre-determined time.
Dangers of Using Code in Events
When you write code to do something when the user takes a certain action, you need to bear in mind that your code could be triggering other events, which could put your code into a continuous loop.
For example, suppose that you use the ‘Change’ event on a worksheet so that when the user puts a value into a cell, a calculation based on that cell is placed into the cell immediately to the right of it.
The problem here is that the placing of the calculated value into the cell triggers another ‘Change’ event, which then in turn triggers yet another ‘Change’ event, and so on until your code has run out of columns to use, and throws up an error message.
You need to think carefully when writing the code for the event to ensure that other events will not be triggered inadvertently
Disable Events
You can use code to disable events to get around this problem. What you will need to do is to incorporate code to disable events whilst your event code is running and then re-enable events at the end of the code. Here is an example of how to do it:
Sub DisableEvents()
Application.EnableEvents = False
Application.EnableEvents = True
End Sub
Bear in mind that this disables all events right across the Excel application, so this would also affect other functions within Excel. If you use this for any reason, make sure that events are switched back on afterwards.
Importance of Parameters in Events
Events usually have parameters which you can use to find out more about what the user is doing and the cell location that they are in.
For example, the Worksheet Change event looks like this:
Private Sub Worksheet_Change(ByVal Target As Range)
By using the range object, you can find out the cell row/column coordinates that the user is actually in.
Private Sub Worksheet_Change(ByVal Target As Range)
MsgBox Target.Column
MsgBox Target.Row
End Sub
If you only want your code to work on a certain column or row number, then you add a condition that exits the subroutine if the column is not the required one.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column <> 2 Then Exit Sub
End Sub
This gets around the problem of your code triggering multiple events, since it will only work if the user has changed a cell in column 2 (column B)
Workbook Events Examples (not exhaustive)
The workbook events are found under the ‘ThisWorkbook’ object in the VBE Project Explorer. You will need to select ‘Workbook’ on the first drop down on the code window and then the second drop down will show you all the events available
Workbook Open Event
This event is fired off whenever the workbook is opened by a user. You could use it to put a welcome message to a user by capturing their username
Private Sub Workbook_Open()
MsgBox "Welcome " & Application.UserName
End Sub
You could also check their username against a list held on a hidden sheet to see if they are authorised to access the workbook. If they are not an authorised user, then you can display a message and close the workbook so that they cannot use it.
Workbook New Sheet Event
This event is triggered when a user adds a new sheet to the workbook
You could use this code to only allow yourself to add a new sheet, rather than have different users all adding sheets and making a mess of the workbook
Private Sub Workbook_NewSheet(ByVal Sh As Object)
Application.DisplayAlerts = False
If Application.UserName <> "Richard" Then
Sh.Delete
End If
Application.DisplayAlerts = True
End Sub
Note that you need to switch off the alerts as a user warning will appear when the sheet is deleted which allows the user to circumvent your code. Make sure that you turn the alerts back on afterwards!
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Workbook Before Save Event
This event is triggered when the user clicks on the ‘Save’ icon, but before the ‘Save’ actually takes place
As described earlier, you may want to prevent users saving their changes to the original workbook, and force them to create a new version using a button on the worksheet. All that you need to do is to change the ‘Cancel’ parameter to True, and the workbook can never be saved by the conventional method.
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Cancel = True
End Sub
Workbook Before Close Event
You can use this event to prevent users closing down the workbook, and again force them to exit through a worksheet button. Again, you set the ‘Cancel’ parameter to ‘True’. The red X in the top right-hand corner of the Excel window no longer works any more.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Cancel = True
End Sub
Worksheet Event Examples (not exhaustive)
The worksheet events are found under the specific sheet name object in the VBE Project Explorer. You will need to select ‘Worksheet’ on the first drop down on the code window and then the second drop down will show you all the events available
VBA Programming | Code Generator does work for you!
Worksheet Change Event
This event is triggered when a user makes a change to a worksheet, such as entering a new value into a cell
You can use this event to put an additional value or comment in next to the changed cell, but as discussed earlier, you do not want to start setting off a loop of events.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column <> 2 Then Exit Sub
ActiveSheet.Cells(Target.Row, Target.Column + 1). Value = _
ActiveSheet.Cells(Target.Row, Target.Column). Value * 1.1
End Sub
In this example, the code will only work if the value is entered into Column B (column 2). If this is true then it will add 10% to the number and place it into the next available cell
Worksheet Before Double Click Event
This event will fire off code if a user double clicks on a cell. This can be extremely useful for financial reports such as a balance sheet or profit & loss account where numbers are likely to be challenged by managers, especially if the bottom line is negative!
You can use this to provide a drill-down facility, so that when the manager challenges a particular number, all they have to do is double click on the number, and the breakdown appears as part of the report.
This is very impressive from a user’s point of view, and saves them constantly asking ‘why is this number so high?’
You would need to write code to find out the heading / criteria for the number (using the Target object properties) and then filter the tabular data and then copy it into the report.
Worksheet Activate Event
This event occurs when the user moves from one sheet to another. It applies to the new sheet that the user is moving to.
It could be used to ensure that the new sheet is completely calculated before the user starts doing anything on it. It can also be used to only re-calculate that particular sheet without re-calculating the entire workbook. If the workbook is large and has complicated formula in it, then re-calculating one sheet saves a lot of time
Private Sub Worksheet_Activate()
ActiveSheet.Calculate
End Sub
Active X Control Events (not exhaustive)
As discussed earlier, you can add Active X controls directly onto a worksheet. These can be command buttons, drop downs, and list boxes
The Active X events are found under the specific sheet name object (where you added the control) in the VBE Project Explorer. You will need to select the name of the Active X control on the first drop down on the code window and then the second drop down will show you all the events available
Command Button Click Event
When you have put a command button onto a spreadsheet, you will want it to take some action. You do this by putting code on the Click event.
You can easily put an ‘Are you sure message?’ on this so that a check is made before your code runs
Private Sub CommandButton1_Click ()
Dim ButtonRet As Variant
ButtonRet = MsgBox("Are you sure that you want to do this?", vbQuestion Or vbYesNo)
If ButtonRet = vbNo Then Exit Sub
End Sub
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Drop Down (Combo Box) Change Event
An Active X drop down has a change event, so that if a user selects a particular item from the drop-down list, you can capture their choice using this event and then write code to adapt other parts of the sheet or workbook accordingly.
Private Sub ComboBox1_Change ()
MsgBox "You selected " & ComboBox1.Text
End Sub
Tick Box (Check Box) Click Event
You can add a tick or check box to a worksheet so as to provide option choices for the user. You can use the click event on it to see if the user has changed anything on this. The values returned are True or False according to whether it has been ticked or not.
Private Sub CheckBox1_Click ()
MsgBox CheckBox1.Value
End Sub
UserForm Events (not exhaustive)
Excel provides the ability for you to design your own forms. These can be very useful to use as pop-ups to collect information or to provide multiple choices to the user. They use Active X controls as described previously and have exactly the same events, although the events depend very much on the type of control.
Here is an example of a simple form:
When it is displayed this is what it looks like on screen
You would use events on the form to do things like enter a default company name when the form is opened, to check the company name input agrees to one already in the spreadsheet and has not been mis-spelt, and to add code to the click events on the ‘OK’ and ‘Cancel’ buttons
The code and events behind the form can be viewed by double clicking anywhere on the form
The first drop down gives access to all the controls on the form. The second drop down will give access to the events
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
UserForm Activate Event
This event is triggered when the form is activated, normally when it is displayed. This event can be used to set up default values e.g. a default company name in the company name text box
Private Sub UserForm_Activate()
TextBox1.Text = "My Company Name"
End Sub
Change Event
Most of the controls on the form have a change event, but in this example, the company name text box can use the event to put a restriction on the length of the company name being entered
Private Sub TextBox1_Change ()
If Len (TextBox1.Text) > 20 Then
MsgBox "The name is restricted to 20 characters", vbCritical
TextBox1.Text = ""
End If
End Sub
Click Event
You can use this event to take action from the user clicking on controls on the form, or even the form itself
On this form there is an ‘OK’ button, and having collected a company name, we would want to place it in a cell on the spreadsheet for future reference
Private Sub CommandButton1_Click ()
ActiveSheet.Range("A1"). Value = TextBox1.Text
Me.Hide
End Sub
This code acts when the user clicks the ‘OK’ button. It puts the value in the company name input box into cell A1 on the active sheet and then hides the form so that user control is returned back to the worksheet.
Chart Events
Chart events only work on charts that are on a separate chart sheet, and not on a chart that is incorporated into a standard worksheet
Chart events are somewhat limited and cannot be used on a worksheet where you might well have multiple charts. Also, users do not necessarily want to switch from a worksheet containing numbers to a chart sheet – there is no immediate visual impact here
The most useful event would be to find out the component of a chart that a user has clicked on e.g. a segment in a pie chart, or a bar in a bar chart, but this is not an event available on the standard range of events.
This problem can be solved by using a class module to add a ‘Mouse Down’ event which will return details of the chart component that the user has clicked on. This is used on a chart within a worksheet.
This involves some very complicated coding, but the results are spectacular. You can create drill downs e.g. the user clicks on a pie chart segment and instantly that chart is hidden and a second chart appears in its place showing a pie chart of detail for the original segment, or you could produce the tabular data supporting that segment of the pie chart.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Application Events
You can use the Application object in VBA to fire off code according to a particular event
Application.OnTime
This can enable you to fire off a piece of code at regular intervals for as long as the workbook is loaded into Excel. You may want to auto-save your workbook to a different folder every 10 minutes, or leave the worksheet running overnight so as to bring in the latest data from an external source.
In this example, a sub routine is entered into a module. It displays a message box to every 5 minutes, although this could easily be another coded procedure. At the same time, it resets the timer to the current time plus 5 more minutes.
Every time it runs, the timer resets to run the same sub routine in another 5 minutes time.
Sub TestOnTime()
MsgBox "Testing OnTime"
Application.OnTime (Now () + TimeValue("00:05:00")), "TestOnTime"
End Sub
Application.OnKey
This function enables you to design your own hot keys. You can make any key combination call a sub routine of your creation.
In this example the letter ‘a’ is redirected so that instead of placing an ‘a’ in a cell, it will display a message box. This code needs to be placed in an inserted module.
Sub TestKeyPress()
Application.OnKey "a", "TestKeyPress"
End Sub
Sub TestKeyPress()
MsgBox "You pressed 'a'"
End Sub
You run the sub routine ‘TestKeyPress’ first of all. You only need to run this once. It tells Excel that every time the letter ‘a’ is pressed it will call the sub routine ‘TestKeyPress’. The sub routine ‘TestKeyPress’ just displays a message box to tell you that you pressed key ‘a’. It could of course load a form or do all sorts of other things.
You can use any key combination that you can use with the ‘SendKeys’ function
To cancel this functionality, you run the ‘OnKey’ statement without the ‘Procedure’ parameter.
Sub CancelOnKey()
Application.OnKey "a"
End Sub
Everything is now back to normal.
Worksheet Selection Change Event in Excel VBA and Preventing Event Loops
Related Links:
Excel VBA Events, Event Handler, Trigger a VBA Macro.
Worksheet Change Event in VBA and Preventing Event Loops.
————————————————————————
Contents:
Worksheet_SelectionChange Event
Preventing Event Loops with Application.EnableEvents = False
————————————————————————
Worksheet_SelectionChange Event:
You can auto run a VBA code, each time that you make a new selection on the worksheet, with the Worksheet_SelectionChange event. The selection change event occurs when the selection changes on a worksheet, either by the user or by any VBA application. The Worksheet_Change event fires when content in a cell changes, while the Worksheet_SelectionChange event fires whenever a new cell is selected.
Worksheet SelectionChange procedure is installed with the worksheet, ie. it must be placed in the code module of the appropriate Sheet object. To create a worksheet SelectionChange event: use the Visual Basic Editor -> in the Project Explorer, double click on the appropriate sheet (under ‘Microsoft Excel Objects’ which is under the VBAProject/name of your workbook) -> in the Code window, select «Worksheet» from the left-side «General» drop-down menu and then select «SelectionChange» from the right-side «Declarations» drop-down menu. You will get a procedure «shell» in the code window as follows:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
End Sub
Target is a parameter of data type Range (ie. Target is a Range Object). It refers to the SelectionChange Range and can consist of one or multiple cells. If Target is in the defined Range, and when the selection changes within this Range, it will trigger the vba procedure. If Target is not in the defined Range, nothing will happen in the worksheet. In this manner, you can limit the events to a particular range for both the Change and SelectionChange events. See the Worksheet Change Event in VBA and Preventing Event Loops page for details on using the Target parameter, Error Handlers and to Enable or Disable Events in a code.
Sample Codes for Worksheet_SelectionChange Event:
Background color of a cell(s) changes to blue each time a new selection is made, only if a single and empty new cell is selected:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Cells.Count = 1 And IsEmpty(Target) Then Target.Interior.Color = vbBlue
End Sub
Increments cell B2 whenever a new cell is selected in column 1 or column 2 (except selection of cells A1 and B1), and if the selected cell is a numeric:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
‘on selecting cell A1 or B1, exit sub
If Target.Address = «$A$1» Or Target.Address = «$B$1» Then Exit Sub
‘if any cell in column 1 or 2 is selected
If Target.Column = 1 Or Target.Column = 2 Then
‘if cell value is numeric
If IsNumeric(Target) Then
‘increment cell B2 value by 1
Range(«B2»).Value = Range(«B2»).Value + 1
End If
End If
End Sub
Preventing Event Loops with Application.EnableEvents = False
Recursive Event Loops (though most common in Worksheet_Change events) might happen in Worksheet_SelectionChange events, as in the following example of a recursive loop code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Target.Offset(1, 1).Select
End Sub
Recursive Event Loop:
If, at each runtime, the Worksheet_SelectionChange event changes the selection of a cell which itself is part of the Target Range (ie. which triggers the SelectionChange event), it will result in reprocessing the SelectionChange event repeatedly. Recursion is the process of repeating in a similar way viz. when the procedure calls itself. Refer to above example of a recursive loop code, if any cell selection in the worksheet is changed by the user, another cell [Offset(1,1)] is selected, which again triggers the SelectionChange event and which will in turn select another cell, and so on. This will result in a recursive loop which might result in a ‘Out Of Stack Space’ untrappable error, or depending on the Excel setting, the loop might terminate at a threshold limit of say 100. To prevent this, enter the following at the beginning of the code: Application.EnableEvents = False. This means that any change made by the VBA code will not trigger any event and will not enable restarting the Worksheet_SelectionChange event. EnableEvents is not automatically changed back to True, this should be specifically done in your code, by adding the following line at the end of the code: Application.EnableEvents = True. Meanwhile, if during runtime, your code encounters an error, you will need an ErrorHandler (to change EnableEvents back to True) because events have been disabled in the beginning of the code. This can be done as follows.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
‘on the occurrence of an error, say selecting cell A1 will cause an error, procedure flow is directed to the error-handling routine (ie. ErrHandler) which handles the error
On Error GoTo ErrHandler
‘to prevent recursion, so that any change made by code will not trigger an event to restart the Worksheet_SelectionChange event
Application.EnableEvents = False
‘on selection of a cell (Target), this procedure selects one cell above the left of the target cell — offsets by 1 row (up) & 1 column (left)
Target.Offset(-1, -1).Select
‘EnableEvents is not automatically changed back to True & hence this needs to be done specifically at the end of the code before exit.
‘because an exit statement (ex. Exit Sub) is not placed above, the error-handling routine will also execute when there is no error.
ErrHandler:
Application.EnableEvents = True
End Sub
IvanMantrov Пользователь Сообщений: 215 |
#1 01.10.2017 11:41:26 Здраствуйте.
Возникла необходимость дублировать эту же функцию на этом же листе, но с другой ячейкой. Попробовал просто объявить еще одну переменную:
Выдает ошибку Изменено: IvanMantrov — 01.10.2017 12:04:29 |
||||
Юрий М Модератор Сообщений: 60570 Контакты см. в профиле |
Вы в названии темы обозначили две переменных — где они? |
vikttur Пользователь Сообщений: 47199 |
#3 01.10.2017 11:47:18
|
||
Юрий М Модератор Сообщений: 60570 Контакты см. в профиле |
#4 01.10.2017 11:51:35
|
||
В смысле недопустимое имя? |
|
Юрий М Модератор Сообщений: 60570 Контакты см. в профиле |
Target — целевая ячейка. А Target2 — просто нет такого. |
vikttur Пользователь Сообщений: 47199 |
Не может быть несколько Target. Как, к примеру, не может быть несколько активных ячеек или активных листов. |
vikttur, понял теперь! Я просто думал это рандомно выбранное имя. |
|
vikttur Пользователь Сообщений: 47199 |
#9 01.10.2017 12:01:09 Так лучше:
|
||
Михаил С. Пользователь Сообщений: 10514 |
#10 01.10.2017 12:04:27
Но Target может быть в нескольких ячейках сразу. |
||
vikttur Пользователь Сообщений: 47199 |
Ну да. Одна ячейка или несколько. Не обязательно в одном диапазоне. |
Ігор Гончаренко Пользователь Сообщений: 13746 |
#12 01.10.2017 13:41:33 IvanMantrov, т.е. можете в модуле листа обьявить
и будете себе на радость получать сообщение что отмечено сейчас, каждый раз как только перенесли курсор на другую ячейку или диапазон ячеек. Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете! |
||
Filipp Kalugin Пользователь Сообщений: 20 |
#13 24.05.2021 16:41:49 Здравствуйте у меня такая проблема я ни могу разобраться как сделать что бы команда .Column <> 21 Then Exit Sub работала ещё и на 24 столбец внизу пробовал просто добавить команду через If .Column но не работает может быть дело в «<>» ?
Изменено: Filipp Kalugin — 24.05.2021 16:42:36 |
||
vikttur Пользователь Сообщений: 47199 |
#14 24.05.2021 16:57:09
|
||
Спасибо большое за помощь. А как понять она к знаку «+» будет относится или для нее отдельно нужен код? |
|
БМВ Модератор Сообщений: 21376 Excel 2013, 2016 |
#16 25.05.2021 07:23:10
По вопросам из тем форума, личку не читаю. |
||
Filipp Kalugin Пользователь Сообщений: 20 |
#17 25.05.2021 07:44:32 Спасибо получается но ни так как бы хотелось у меня при выполнение данного кода Excel подвисает мне получается нужно если в колонке 21 значение «+» то в в 5 колонке становится «П» и цвет желтый а если в колонке 24 поставить значение «-» то там должна быть значение «В» и она красного цвета должна быть.
|
||
БМВ Модератор Сообщений: 21376 Excel 2013, 2016 |
#18 25.05.2021 07:57:38
По вопросам из тем форума, личку не читаю. |
||
Filipp Kalugin Пользователь Сообщений: 20 |
#19 25.05.2021 08:39:10 Не получилось(
Изменено: Filipp Kalugin — 25.05.2021 08:43:35 |
||
и не получится пока не обьясните задачу Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете! |
|
Filipp Kalugin Пользователь Сообщений: 20 |
#21 25.05.2021 09:06:18 Задача вот какая есть документ Файл в нём надо сделать так что бы в столбце «X» при значение «-» в столбце «E» ставилась буква «В» и ячейка становилась красной. Мне с такой задачей тут уже помоги я хотел на ее основе сделать эту задачу и совместить что бы оба кода работали в одном документе. Вот первый код к нему надо прибавить задачу которая сверху!
Изменено: Filipp Kalugin — 25.05.2021 09:06:50 |
||
код не нужен, нужно описание задачи Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете! |
|
Filipp Kalugin Пользователь Сообщений: 20 |
#23 25.05.2021 09:40:10 В столбце «Х» есть формула «=V2-W2» то есть когда значение будет равно -1 в столбце «Е» в ячейках должна ставится буква «В» и ячейка должна быть красного цвета. Изменено: Filipp Kalugin — 25.05.2021 09:40:59 |