Worksheet change vba excel не работает
Я использую VBA для изменения Excel и имею следующий простой обработчик событий внутри Sheet1:
Это никогда не срабатывает, никогда. Я тестировал в Immediate Window:
который в конечном итоге возвращает True, поэтому он должен срабатывать. Кто-нибудь знает, почему это вообще не хочет стрелять?
задан 25 июля '12, 18:07
Глупые вопросы: код находится в Sheet1, а не в модуле? Находится ли он на правильном Sheet1 (скажем, у вас открыты 2 книги, и у обеих есть Sheet1)? - assylias
Кроме того, что вы делаете, что вы ожидаете, что событие сработает? - Daniel
Есть только одна рабочая книга, и да, она находится на Листе 1, и мы работаем на Листе 1. У меня есть код в модуле, и эти сабвуферы работают нормально. - У меня есть столбец, в котором я хочу, чтобы люди вводили частоту обновления для RTD.ThrottleInterval, чтобы пользователь мог изменить скорость обновления Excel из RTD - JamesD31
Я проверил приведенный выше код, и он отлично работает. Как происходят изменения в клетке? Вручную или по формуле? - Siddharth Rout
Вручную, поскольку это событие должно срабатывать при любых изменениях, я просто вводил случайные ячейки и нажимал ввод, но ничего не происходит. - JamesD31
3 ответы
У вас больше одного листа? Имейте в виду, что свойство CodeName листа и свойство Name (имя на вкладке в Excel) не всегда совпадают. Например, если в Project Explorer есть список
Затем Sheet1 — это имя, а Sheet2 — это кодовое имя.
Самый простой способ убедиться, что вы поместили код не в тот модуль, — щелкнуть правой кнопкой мыши вкладку листа и выбрать «Просмотреть код». Это вызовет CodePane для этого листа, и именно там должен быть ваш код.
Создан 25 июля '12, 19:07
Ваш способ сработал, кажется, и я не знаю как, но у меня было следующее: Лист1 Лист2 Лист3 Лист4(Лист1). И вот я только что протестировал "Лист4(Лист1)" и он работал, тогда как раньше я просто тестировал в Sheet1 - JamesD31
Этот вопрос был опубликован давно, но недавно у меня была такая же проблема. Если есть другие новички в vba, которые борются с этим, попробуйте сохранить свою книгу и снова открыть ее. После того, как я это сделал, Worksheet_Change Sub на моем листе сработал, как я и ожидал.
Возможно, есть элемент управления для компиляции подчиненных листов, который мне не хватало.
Я нашел проблему, хотя. Если отладчик выдает ошибку, а вы говорите отладка, события не будут работать, пока вы не прекратите отладку. - Талха Талип Ачикгёз
В 2018 году это все еще ошибка в Excel. Никакое другое решение не сработало, но мне пришлось закрыть Excel и снова открыть книгу. Вуаля! - Фанданго68
Обычно используется с Target . Вот пример, если вы выделите M4 и измените значение, посмотрите, что произойдет:
ВОТ довольно хороший пост об этом событии
Хорошо - см. комментарии ниже + я только что проверил, и ваш код должен работать. Попробуй это? Это тоже не работает?
Создан 25 июля '12, 19:07
хорошо - только что проверил код OPers на моей машине, и вы правы - цель не требуется; странный! - почему
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками events vba excel or задайте свой вопрос.
I have a sheet where I enter times ( from and to ) in columns H and I and columns J and K are supposed to show duration minutes and hours, respectively. Below is the code I came up with. I placed it in the Worksheet (not module) as I want the result to be volatile (instant). What it does is it updates every time I select a row of the updated cell. It also cleared contents of the header of the columns J and K. I keep it as SelectionChange. When I set it up as Change it freezes and I have to shut down excel.
How do I make it right so it returns as expected?
Thank you all in advance.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim r, c
Worksheets("NonWrench_Wrench Time").Select
If Cells(r, 8) = "" Or Cells(r, 9) = "" Or Cells(r, 9) < Cells(r, 8) Then
Cells(r, 10) = (Cells(r, 9) - Cells(r, 8)) * 1440
Cells(r, 11) = (Cells(r, 9) - Cells(r, 8)) * 1440 / 60
On Error GoTo 0
This thread is locked. You can follow the question or vote as helpful, but you cannot reply to this thread.
Report abuse
Harassment is any behavior intended to disturb or upset a person or group of people. Threats include any threat of suicide, violence, or harm to another. Any content of an adult theme or inappropriate to a community web site. Any image, link, or discussion of nudity. Any behavior that is insulting, rude, vulgar, desecrating, or showing disrespect. Any behavior that appears to violate End user license agreements, including providing product keys or links to pirated software. Unsolicited bulk mail or bulk advertising. Any link to or advocacy of virus, spyware, malware, or phishing sites. Any other inappropriate content or behavior as defined by the Terms of Use or Code of Conduct. Any image, link, or discussion related to child pornography, child nudity, or other child abuse or exploitation.
Replies (6)
There is a code module for each worksheet.
There is a standard/general code module.
There is a Class module.
And there is a UserForm module.
With code using Events (your example), it is necessary (most of the time) to turn off Event processing to prevent runaways/crashes.
A change runs the code which changes something which causes the Event code to repeat and so on.
The code statement to turn off events is: Application.EnableEvents = False
Using this statement requires it to be set to True before exiting the code.
That means you need an error handler to trap errors and enable events.
Also, every exit point in the code needs to enable events.
That said, why not just use formulas on the worksheet to handle your calculations?
'---
Free Exce add-ins and workbooks at MediaFire.
Report abuse
Harassment is any behavior intended to disturb or upset a person or group of people. Threats include any threat of suicide, violence, or harm to another. Any content of an adult theme or inappropriate to a community web site. Any image, link, or discussion of nudity. Any behavior that is insulting, rude, vulgar, desecrating, or showing disrespect. Any behavior that appears to violate End user license agreements, including providing product keys or links to pirated software. Unsolicited bulk mail or bulk advertising. Any link to or advocacy of virus, spyware, malware, or phishing sites. Any other inappropriate content or behavior as defined by the Terms of Use or Code of Conduct. Any image, link, or discussion related to child pornography, child nudity, or other child abuse or exploitation.
Was this reply helpful?
Sorry this didn't help.
Great! Thanks for your feedback.
How satisfied are you with this reply?
Thanks for your feedback, it helps us improve the site.
How satisfied are you with this reply?
Thanks for your feedback.
There is a code module for each worksheet.
There is a standard/general code module.
There is a Class module.
And there is a UserForm module.
With code using Events (your example), it is necessary (most of the time) to turn off Event processing to prevent runaways/crashes.
A change runs the code which changes something which causes the Event code to repeat and so on.
The code statement to turn off events is: Application.EnableEvents = False
Using this statement requires it to be set to True before exiting the code.
That means you need an error handler to trap errors and enable events.
Also, every exit point in the code needs to enable events.
That said, why not just use formulas on the worksheet to handle your calculations?
'---
Free Exce add-ins and workbooks at MediaFire.
Thanks for your response. Originally I did have formulas in my spreadsheet. The table in the spreadsheet has 1000 lines with multiple conditional formats. With the empty (not filled in) state it is heavy and will likely crash. That is the reason I deiced to "codify" the columns as it will make a little lighter.
Thank you for your suggestion which is very relevant to this case, but I still need VBA coding assistance with my question.
Report abuse
Harassment is any behavior intended to disturb or upset a person or group of people. Threats include any threat of suicide, violence, or harm to another. Any content of an adult theme or inappropriate to a community web site. Any image, link, or discussion of nudity. Any behavior that is insulting, rude, vulgar, desecrating, or showing disrespect. Any behavior that appears to violate End user license agreements, including providing product keys or links to pirated software. Unsolicited bulk mail or bulk advertising. Any link to or advocacy of virus, spyware, malware, or phishing sites. Any other inappropriate content or behavior as defined by the Terms of Use or Code of Conduct. Any image, link, or discussion related to child pornography, child nudity, or other child abuse or exploitation.
Was this reply helpful?
Sorry this didn't help.
Great! Thanks for your feedback.
How satisfied are you with this reply?
Thanks for your feedback, it helps us improve the site.
How satisfied are you with this reply?
Thanks for your feedback.
The following code appears to work, give it a try.
(code goes in the worksheet module)
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo BadEntry
Dim R As Long
If Target(1).Column < 8 Or Target(1).Column >9 Then
Exit Sub
Else
R = Target(1).Row
If Me.Cells(R, 8) = vbNullString Or Me.Cells(R, 9) = vbNullString Or _
Me.Cells(R, 9) < Me.Cells(R, 8) Then
Me.Cells(R, 10) = vbNullString
Me.Cells(R, 11) = vbNullString
Else
'not really necessary as code exits if columns 10 / 11 are changed.
Application.EnableEvents = False
Me.Cells(R, 10) = (Me.Cells(R, 9) - Me.Cells(R, 8)) * 1440
Me.Cells(R, 11) = (Me.Cells(R, 9) - Me.Cells(R, 8)) * 1440 / 60
End If
End If
Application.EnableEvents = True
Exit Sub
BadEntry:
VBA.MsgBox Err.Description & " - " & Err.Number
Application.EnableEvents = True
End Sub
Report abuse
Harassment is any behavior intended to disturb or upset a person or group of people. Threats include any threat of suicide, violence, or harm to another. Any content of an adult theme or inappropriate to a community web site. Any image, link, or discussion of nudity. Any behavior that is insulting, rude, vulgar, desecrating, or showing disrespect. Any behavior that appears to violate End user license agreements, including providing product keys or links to pirated software. Unsolicited bulk mail or bulk advertising. Any link to or advocacy of virus, spyware, malware, or phishing sites. Any other inappropriate content or behavior as defined by the Terms of Use or Code of Conduct. Any image, link, or discussion related to child pornography, child nudity, or other child abuse or exploitation.
Was this reply helpful?
Sorry this didn't help.
Great! Thanks for your feedback.
How satisfied are you with this reply?
Thanks for your feedback, it helps us improve the site.
How satisfied are you with this reply?
Thanks for your feedback.
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo BadEntry
Dim R As Long
Dim C As Long
If Target(1).Column < 8 Or Target(1).Column >9 Then
Exit Sub
Else
R = Target(1).Row
C = Target(1).Column
If Me.Cells(R, 8) = vbNullString Or Me.Cells(R, 9) = vbNullString Or _
Me.Cells(R, 9) < Me.Cells(R, 8) Then
Me.Cells(R, 10) = vbNullString
Me.Cells(R, 11) = vbNullString
Else
'not really necessary as code exits if columns 10 / 11 are changed.
Application.EnableEvents = False
Me.Cells(R, 10) = (Me.Cells(R, 9) - Me.Cells(R, 8)) * 1440
Me.Cells(R, 11) = (Me.Cells(R, 9) - Me.Cells(R, 8)) * 1440 / 60
End If
End If
Application.EnableEvents = True
Exit Sub
BadEntry:
VBA.MsgBox Err.Description & " - " & Err.Number
Application.EnableEvents = True
End Sub
Thanks for your response.
It worked but not completely responsive. When the entries are entered in columns H and I only that row gets updated. If several lines of data are copied over to H and I, then the outcome shows up only on the first row (blue circle), the rest (below) show blank. Also, when the entry data is deleted (black circle) the results in columns J and K still show and not removed. Please see below the image of the spreadsheet when I use your code. Thank you.
Hi, my VBA code for a budget spreadsheet has a Worksheet_Change procedure with Intersect and target as part of it.
When users copy and paste a cell using their mouse to Edit, Copy then Edit, Paste, the spreadsheet freezes. But if they use the Ctrl C and V to copy paste, it does not freeze. When I step thru the code in both scenarios, it follows the same path thru the Ifs and End Ifs, etc. Yet one way freezes and the other doesn't.
In these scenarios the copy paste actions are not within the target, so the two Ifs solve to 'Nothing', so most of the code is skipped. Yet it still freezes when using the mouse.
When it freezes, using the mouse, the only way I can get out of it (other than closing Excel), is to hit F5 GoTo, then choose a reference that is on another sheet. It will change to that sheet. I can then come back to the first sheet and continue as normal.
I can't figure out how to fix this. Would sure appreciate some help!
This thread is locked. You can follow the question or vote as helpful, but you cannot reply to this thread.
Report abuse
Harassment is any behavior intended to disturb or upset a person or group of people. Threats include any threat of suicide, violence, or harm to another. Any content of an adult theme or inappropriate to a community web site. Any image, link, or discussion of nudity. Any behavior that is insulting, rude, vulgar, desecrating, or showing disrespect. Any behavior that appears to violate End user license agreements, including providing product keys or links to pirated software. Unsolicited bulk mail or bulk advertising. Any link to or advocacy of virus, spyware, malware, or phishing sites. Any other inappropriate content or behavior as defined by the Terms of Use or Code of Conduct. Any image, link, or discussion related to child pornography, child nudity, or other child abuse or exploitation.
I think I have got to the bottom of this one - there are 3 issues here.
1. As noted above the maro leaves ScreenUpdating set to false
2. From the tests I have done, it looks like Excel will usually reset ScreenUpdating to TRUE all on its own - unless there are a lot of changes made to the sheet - e.g. delete a row or two
3. Harold's Change macro does not appear to have protection against being re-entered if the marco itself changes the content of the sheet.
Private Sub Worksheet_Change(ByVal Target As Range)
'
Application.ScreenUpdating = False
Range("B1").Value = Range("B1").Value + 1
End Sub
If you change ONE cell on the sheet which has this Change macro, the count will (unexpectedly) be 96 or 97. Sometimes the screen freezes, sometimes it does not.
I suggest that this is due to the macro being called again (and again) when the value in B1 is incremented by the Chnage macro. Somewhere inside Excel this goes up a loop and then decides that it has done enough / its job and it exits. Usually ScreenUpdating is TRUE on exit, other times it is not. If you try to test the value of this in the immediate window it is reported to be false and then (all on its own) flips to TRUE (I kid you not).
The behaviour is variable - on one test, deleteing a row generated an "Out of stack space" error.
1. If you want to change cell vaules on the sheet to which the Change maro belongs, you MUST make the code non-renterant - see below
2. If you 'manage' system parameters such as ScreenUpdating on entry to a maro, you must remember to set them back to something sensible on exit.
3. When the screen was left frozen I suspect that a 'quiet' stack over flow occurred leaving ScreenUpdating set to FALSE.
Suggested full solution. code to be placed on the worksheet object
'Control flag variable that exists outside of the macro to inhibit re-entry
PUBLIC blnChangeActive as boolean
Private Sub Worksheet_Change(ByVal Target As Range)
'
'Look to see if this code is already active, if it is go away!
if blnChangeActive then Exit Sub
'Set the macro is active flag so that changes made to this sheet in this macro do not
'cause this macro to run again
blnChangeActive = true
'Inhibit screen updating to make the code run faster and avoid screen flashing
Application.ScreenUpdating = False
'
' This is where the Change macro code goes. whatever you want to do!
'
'For example my cell value incrementer.
Range("B1").Value = Range("B1").Value + 1
'Enable screen updating again
Application.ScreenUpdating = True
'Remove the reentry lock
blnChangeActive = false
End Sub
The above macro results in the value of B1 being increment by only 1 - as might have been expected!
My Excel project functions properly at home (with Excel 2010), but not on two work computers (with Excel 2016) and I suspect the Worksheet_Change event is the problem.
When the user makes changes, the yellow bar (in the screenshot) should turn white again, but it is not. I am getting 2 different responses on 2 work computers.
Two things to point out in the code:
In some places I use vbColor extensions, in others I had to use a numerical code.
One computer is not firing the Worksheet_Change event at all. I would note that the change event is at the top of the code, although that shouldn't have anything to do with it.
I'd appreciate advice and detailed explanations, to help me learn.
not firing the Worksheet_Change could be security settings, for the color try using Excel RGB color example .Color = RGB(0, 0, 0)
^ For firing events try running this line Application.EnableEvents = True , for the white bar place a break point on line If Range("L3").Value > Range("I3").Value and check the values for both cells (and time format)
@pica - again, he would have had to disable Events at some point in his code; I don't understand what leads you to believe he did that? i don't mean to argue - just curious what lead to that "hunch". Also - a quick way to confirm is [CTRL]+[G] then ?Application.EnableEvents and [Enter] .
4 Answers 4
There could be a number of factors causing this problem. One way to diagnose is to troubleshoot like this:
At the beginning of your procedure, right after this line:
. add a temporary line:
. then go change something in your worksheet (whatever change isn't firing the event as you'd expect).
One of two things will happen:
You'll have a message box pop up, showing the cell reference of whatever was just changed.
This demonstrates that the event is firing properly, so the issue must be in your code that follows.
Or, you won't get a message box pop up. This indicates the event is not firing, which could be caused by a few possibilities:
Are macros completely disabled in the workbook? This is often done automatically on workbooks received from outside sources. Save the workbook to a trusted location on the local computer or network (rather than opening from the email). Do other sections of code run properly? When you close/re-open the file, are you given a warning about Macro Security? Also, try rebooting the computer.
Other security settings could be an issue. Have you ever run VBA on these machines? You can confirm sure code is able to run in Excels' security settings in:
File → Options → Trust Center → Trust Center Settings → Macro Settings
As well as making sure macros are enabled there, you could also check Trusted Locations in the Trust Center, and either save your document in a listed location, or add a new location. Security settings will be "reduced" for documents saved in those locations.
Is EnableEvents being intentionally disabled elsewhere in your code? If you wrote all the code, you should know whether you set EnableEvents = False at some point. Perhaps it was intentional, but it's not being re-enabled.
Remember to remove the line you added temporarily, or that MsgBox will quickly get annoying by popping up every time a change is made. :)
= Мир MS Excel/Worksheet_Change - Мир MS Excel
Войти через uID
Войти через uID
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
Dim w As Object
If Range("E23") = "5х1,5" Then
Range("K23:M23") = "-"
Range("H23:J23,N23:T23") = ""
Application.EnableEvents = True
End Sub
[/vba]Важно, что бы макрос запускался автоматически после ввода определенного значения
(он указывает в какие ячейки в дальнейшем нужно ввести значения)
В этом случае нет возможности что-то поменять в ячейках K23:M23 и (H23:J23,N23:T23), а это принципиально.
Возможность убрать (= "") не проходит, т.к. в дальнейшем например:[vba]
[/vba]Может быть есть какая-то возможность остановить либо завершить процедуру Worksheet_Change,
после ввода "5х1,5",тем самым оставляя возможность вручную подкорректировать ячейки не удаляя
значение Range("E23"), а затем начать процедуру Worksheet_Change снова, но уже в другой ячейке.
Может быть существует какое-то другое решение этой проблемы?
Например с кнопкой это работает так:[vba]
Private Sub Кнопка1_Click()
If Cells(23, 5) = "" Then
Range("H23:T23").Interior.ColorIndex = x6None
Cells(23, 5).Interior.ColorIndex = 3
MsgBox ("Введите значение!")
Range("H23:T23") = "-"
End If
If Cells(23, 5) = "5х1,5" Then
Range("K23:M23") = "-"
Range("H23:J23,N23:T23") = ""
Range("H23:T23").Interior.ColorIndex = x6None
Range("H23:J23,N23:T23").Interior.ColorIndex = 6
Range("E23:E23").Interior.ColorIndex = x3None
End If
If Cells(23, 5) = "4х1,5" Then
Range("N23:T23") = "-"
Range("H23:M23") = ""
Range("H23:T23").Interior.ColorIndex = x6None
Range("H23:M23").Interior.ColorIndex = 6
Range("E23:E23").Interior.ColorIndex = x3None
End If
If Cells(23, 5) = "3х1,5" Then
Dim A As Variant
A = InputBox("Введите номер: 1,2 или 3", "Ввод данных")
Select Case A
Case 1
Range("H23:M23,O23:P23,R23:S23") = "-"
Range("N23:N23,Q23:Q23,T23:T23") = ""
Range("E23:E23").Interior.ColorIndex = x3None
Range("N23:N23,Q23:Q23,T23:T23").Interior.ColorIndex = 6
Range("H23:M23").Interior.ColorIndex = x6None
Range("O23:O23,R23:R23,P23:P23,S23:S23").Interior.ColorIndex = x6None
Case 2
Range("H23:N23,P23:Q23,S23:S23") = "-"
Range("O23:O23,R23:R23,T23:T23") = ""
Range("E23:E23").Interior.ColorIndex = x3None
Range("O23:O23,R23:R23,T23:T23").Interior.ColorIndex = 6
Range("H23:M23").Interior.ColorIndex = x6None
Range("N23:N23,Q23:Q23,P23:P23,S23:S23").Interior.ColorIndex = x6None
Case 3
Range("H23:O23,Q23:R23") = "-"
Range("P23:P23,S23:S23,T23:T23") = ""
Range("E23:E23").Interior.ColorIndex = x3None
Range("P23:P23,S23:S23,T23:T23").Interior.ColorIndex = 6
Range("H23:M23").Interior.ColorIndex = x6None
Range("N23:N23,Q23:Q23,O23:O23,R23:R23").Interior.ColorIndex = x6None
End Select
End If
[/vba]__________________________________________________________________________________________
Как же сделать то же но без кнопки (автоматически).
Необходимость в[vba]
If Cells(23, 5) = "" Then
Range("H23:T23").Interior.ColorIndex = x6None
Cells(23, 5).Interior.ColorIndex = 3
MsgBox ("Введите значение!")
Range("H23:T23") = "-"
End If
Заранее приношу извинения. Я уверен, что код нелепый и банальный.
Скорее всего можно сделать что-то такое, но гораздо умнее (не на уровне 1-го класса).
К сожалению я не знаю как. Прошу понять, откликнуться и помочь.
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
Dim w As Object
If Range("E23") = "5х1,5" Then
Range("K23:M23") = "-"
Range("H23:J23,N23:T23") = ""
Application.EnableEvents = True
End Sub
[/vba]Важно, что бы макрос запускался автоматически после ввода определенного значения
(он указывает в какие ячейки в дальнейшем нужно ввести значения)
В этом случае нет возможности что-то поменять в ячейках K23:M23 и (H23:J23,N23:T23), а это принципиально.
Возможность убрать (= "") не проходит, т.к. в дальнейшем например:[vba]
[/vba]Может быть есть какая-то возможность остановить либо завершить процедуру Worksheet_Change,
после ввода "5х1,5",тем самым оставляя возможность вручную подкорректировать ячейки не удаляя
значение Range("E23"), а затем начать процедуру Worksheet_Change снова, но уже в другой ячейке.
Может быть существует какое-то другое решение этой проблемы?
Например с кнопкой это работает так:[vba]
Private Sub Кнопка1_Click()
If Cells(23, 5) = "" Then
Range("H23:T23").Interior.ColorIndex = x6None
Cells(23, 5).Interior.ColorIndex = 3
MsgBox ("Введите значение!")
Range("H23:T23") = "-"
End If
If Cells(23, 5) = "5х1,5" Then
Range("K23:M23") = "-"
Range("H23:J23,N23:T23") = ""
Range("H23:T23").Interior.ColorIndex = x6None
Range("H23:J23,N23:T23").Interior.ColorIndex = 6
Range("E23:E23").Interior.ColorIndex = x3None
End If
If Cells(23, 5) = "4х1,5" Then
Range("N23:T23") = "-"
Range("H23:M23") = ""
Range("H23:T23").Interior.ColorIndex = x6None
Range("H23:M23").Interior.ColorIndex = 6
Range("E23:E23").Interior.ColorIndex = x3None
End If
If Cells(23, 5) = "3х1,5" Then
Dim A As Variant
A = InputBox("Введите номер: 1,2 или 3", "Ввод данных")
Select Case A
Case 1
Range("H23:M23,O23:P23,R23:S23") = "-"
Range("N23:N23,Q23:Q23,T23:T23") = ""
Range("E23:E23").Interior.ColorIndex = x3None
Range("N23:N23,Q23:Q23,T23:T23").Interior.ColorIndex = 6
Range("H23:M23").Interior.ColorIndex = x6None
Range("O23:O23,R23:R23,P23:P23,S23:S23").Interior.ColorIndex = x6None
Case 2
Range("H23:N23,P23:Q23,S23:S23") = "-"
Range("O23:O23,R23:R23,T23:T23") = ""
Range("E23:E23").Interior.ColorIndex = x3None
Range("O23:O23,R23:R23,T23:T23").Interior.ColorIndex = 6
Range("H23:M23").Interior.ColorIndex = x6None
Range("N23:N23,Q23:Q23,P23:P23,S23:S23").Interior.ColorIndex = x6None
Case 3
Range("H23:O23,Q23:R23") = "-"
Range("P23:P23,S23:S23,T23:T23") = ""
Range("E23:E23").Interior.ColorIndex = x3None
Range("P23:P23,S23:S23,T23:T23").Interior.ColorIndex = 6
Range("H23:M23").Interior.ColorIndex = x6None
Range("N23:N23,Q23:Q23,O23:O23,R23:R23").Interior.ColorIndex = x6None
End Select
End If
[/vba]__________________________________________________________________________________________
Как же сделать то же но без кнопки (автоматически).
Необходимость в[vba]
If Cells(23, 5) = "" Then
Range("H23:T23").Interior.ColorIndex = x6None
Cells(23, 5).Interior.ColorIndex = 3
MsgBox ("Введите значение!")
Range("H23:T23") = "-"
End If
Заранее приношу извинения. Я уверен, что код нелепый и банальный.
Скорее всего можно сделать что-то такое, но гораздо умнее (не на уровне 1-го класса).
К сожалению я не знаю как. Прошу понять, откликнуться и помочь. Dмитрий
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
Dim w As Object
If Range("E23") = "5х1,5" Then
Range("K23:M23") = "-"
Range("H23:J23,N23:T23") = ""
Application.EnableEvents = True
End Sub
[/vba]Важно, что бы макрос запускался автоматически после ввода определенного значения
(он указывает в какие ячейки в дальнейшем нужно ввести значения)
В этом случае нет возможности что-то поменять в ячейках K23:M23 и (H23:J23,N23:T23), а это принципиально.
Возможность убрать (= "") не проходит, т.к. в дальнейшем например:[vba]
[/vba]Может быть есть какая-то возможность остановить либо завершить процедуру Worksheet_Change,
после ввода "5х1,5",тем самым оставляя возможность вручную подкорректировать ячейки не удаляя
значение Range("E23"), а затем начать процедуру Worksheet_Change снова, но уже в другой ячейке.
Может быть существует какое-то другое решение этой проблемы?
Например с кнопкой это работает так:[vba]
Private Sub Кнопка1_Click()
If Cells(23, 5) = "" Then
Range("H23:T23").Interior.ColorIndex = x6None
Cells(23, 5).Interior.ColorIndex = 3
MsgBox ("Введите значение!")
Range("H23:T23") = "-"
End If
If Cells(23, 5) = "5х1,5" Then
Range("K23:M23") = "-"
Range("H23:J23,N23:T23") = ""
Range("H23:T23").Interior.ColorIndex = x6None
Range("H23:J23,N23:T23").Interior.ColorIndex = 6
Range("E23:E23").Interior.ColorIndex = x3None
End If
If Cells(23, 5) = "4х1,5" Then
Range("N23:T23") = "-"
Range("H23:M23") = ""
Range("H23:T23").Interior.ColorIndex = x6None
Range("H23:M23").Interior.ColorIndex = 6
Range("E23:E23").Interior.ColorIndex = x3None
End If
If Cells(23, 5) = "3х1,5" Then
Dim A As Variant
A = InputBox("Введите номер: 1,2 или 3", "Ввод данных")
Select Case A
Case 1
Range("H23:M23,O23:P23,R23:S23") = "-"
Range("N23:N23,Q23:Q23,T23:T23") = ""
Range("E23:E23").Interior.ColorIndex = x3None
Range("N23:N23,Q23:Q23,T23:T23").Interior.ColorIndex = 6
Range("H23:M23").Interior.ColorIndex = x6None
Range("O23:O23,R23:R23,P23:P23,S23:S23").Interior.ColorIndex = x6None
Case 2
Range("H23:N23,P23:Q23,S23:S23") = "-"
Range("O23:O23,R23:R23,T23:T23") = ""
Range("E23:E23").Interior.ColorIndex = x3None
Range("O23:O23,R23:R23,T23:T23").Interior.ColorIndex = 6
Range("H23:M23").Interior.ColorIndex = x6None
Range("N23:N23,Q23:Q23,P23:P23,S23:S23").Interior.ColorIndex = x6None
Case 3
Range("H23:O23,Q23:R23") = "-"
Range("P23:P23,S23:S23,T23:T23") = ""
Range("E23:E23").Interior.ColorIndex = x3None
Range("P23:P23,S23:S23,T23:T23").Interior.ColorIndex = 6
Range("H23:M23").Interior.ColorIndex = x6None
Range("N23:N23,Q23:Q23,O23:O23,R23:R23").Interior.ColorIndex = x6None
End Select
End If
[/vba]__________________________________________________________________________________________
Как же сделать то же но без кнопки (автоматически).
Необходимость в[vba]
If Cells(23, 5) = "" Then
Range("H23:T23").Interior.ColorIndex = x6None
Cells(23, 5).Interior.ColorIndex = 3
MsgBox ("Введите значение!")
Range("H23:T23") = "-"
End If
Заранее приношу извинения. Я уверен, что код нелепый и банальный.
Скорее всего можно сделать что-то такое, но гораздо умнее (не на уровне 1-го класса).
К сожалению я не знаю как. Прошу понять, откликнуться и помочь. Автор - Dмитрий
Дата добавления - 22.09.2013 в 02:08
зы. и что такое x6None и x3None у меня редактор на них ругается.
зы.зы. Не совсем понял, что вам нужно, но может это?
[vba]
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
Dim w As Object
If Target.Address = "$A$23" Then
If Target = "5х1,5" Then ' здесь х - кирилица
Range("K23:M23") = "-"
Range("H23:J23,N23:T23") = ""
End If
End If
Application.EnableEvents = True
End Sub
зы. и что такое x6None и x3None у меня редактор на них ругается.
зы.зы. Не совсем понял, что вам нужно, но может это?
[vba]
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
Dim w As Object
If Target.Address = "$A$23" Then
If Target = "5х1,5" Then ' здесь х - кирилица
Range("K23:M23") = "-"
Range("H23:J23,N23:T23") = ""
End If
End If
Application.EnableEvents = True
End Sub
зы. и что такое x6None и x3None у меня редактор на них ругается.
зы.зы. Не совсем понял, что вам нужно, но может это?
[vba]
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
Dim w As Object
If Target.Address = "$A$23" Then
If Target = "5х1,5" Then ' здесь х - кирилица
Range("K23:M23") = "-"
Range("H23:J23,N23:T23") = ""
End If
End If
Application.EnableEvents = True
End Sub
Суть в следующем: При вводе в ячейку "Е23" значения 5х1,5 (кирилица) макрос автоматически запускается и ставит прочерки в ячейки, которые должны оставаться незаполненными, а остальные должны иметь возможность ручного ввода значений, не изменяя при этом "Е23". Таких ячеек будет множество. Значения в "Е23" будут вводится различные.
Примерно о работе кода можно судить в прикрепленном файле. Беда лишь в том, что макрос работает от кнопки.
Должна же быть возможность автоматически запустить макрос. Я попробовал при помощи Worksheet_Change
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
Dim w As Object
If Range("E23") = "5х1,5" Then
Range("K23:M23") = "-"
Range("H23:J23,N23:T23") = ""
End If
Application.EnableEvents = True
End Sub
[/vba]
но столкнулся с проблемой
Нет возможности что-то поменять в ячейках K23:M23 и (H23:J23,N23:T23), а это принципиально.
Суть в следующем: При вводе в ячейку "Е23" значения 5х1,5 (кирилица) макрос автоматически запускается и ставит прочерки в ячейки, которые должны оставаться незаполненными, а остальные должны иметь возможность ручного ввода значений, не изменяя при этом "Е23". Таких ячеек будет множество. Значения в "Е23" будут вводится различные.
Примерно о работе кода можно судить в прикрепленном файле. Беда лишь в том, что макрос работает от кнопки.
Должна же быть возможность автоматически запустить макрос. Я попробовал при помощи Worksheet_Change
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
Dim w As Object
If Range("E23") = "5х1,5" Then
Range("K23:M23") = "-"
Range("H23:J23,N23:T23") = ""
End If
Application.EnableEvents = True
End Sub
[/vba]
но столкнулся с проблемой
Нет возможности что-то поменять в ячейках K23:M23 и (H23:J23,N23:T23), а это принципиально. Dмитрий
Суть в следующем: При вводе в ячейку "Е23" значения 5х1,5 (кирилица) макрос автоматически запускается и ставит прочерки в ячейки, которые должны оставаться незаполненными, а остальные должны иметь возможность ручного ввода значений, не изменяя при этом "Е23". Таких ячеек будет множество. Значения в "Е23" будут вводится различные.
Примерно о работе кода можно судить в прикрепленном файле. Беда лишь в том, что макрос работает от кнопки.
Должна же быть возможность автоматически запустить макрос. Я попробовал при помощи Worksheet_Change
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
Dim w As Object
If Range("E23") = "5х1,5" Then
Range("K23:M23") = "-"
Range("H23:J23,N23:T23") = ""
End If
Application.EnableEvents = True
End Sub
[/vba]
но столкнулся с проблемой
Нет возможности что-то поменять в ячейках K23:M23 и (H23:J23,N23:T23), а это принципиально. Автор - Dмитрий
Дата добавления - 22.09.2013 в 13:04
Читайте также: