Перейти до основного матеріалу

Як зробити певну комірку обов’язковою для введення перед закриттям книги?

Наприклад, коли ви ділитеся робочою книгою з іншими користувачами для проведення опитування, яке потребує реєстрації справжнього імені, наприклад, кожен досліджуваний користувач повинен ввести своє ім’я в B1. Але іноді деякі користувачі можуть закрити книгу після розслідування, не вводячи своїх імен. У цій статті я представляю VBA, щоб зробити певну комірку обов’язковою перед закриттям книги.

Зробіть комірку обов’язковою для введення за допомогою VBA


стрілка синя права міхур Зробіть комірку обов’язковою для введення за допомогою VBA

1. Увімкніть книгу, яка містить обов’язкову комірку, та натисніть Alt + F11 клавіші, щоб відкрити Microsoft Visual Basic для додатків вікна.

2 В Проекти на панелі, двічі клацніть ThisWorkbookі перейдіть до вибору робочий зошит та ПередЗакрити з правого списку розділів, а потім вставте код нижче в сценарій. Дивіться знімок екрана:

VBA: зробіть клітинку обов’язковою

    If Cells(1, 2).Value = "" Then
        MsgBox "Cell B1 requires user input", vbInformation, "Kutools for Excel"
        Cancel = True
    End If

док мандатури введіть 1

3. Потім збережіть цей код і закрийте це спливаюче вікно. Тепер, якщо клітинка B1 порожня, коли ви закриваєте книгу, відкриється діалогове вікно, яке нагадуватиме вам про те, щоб ввести щось у B1. Дивіться знімок екрана:
док мандатури введіть 2

Чайові: Ви можете змінити клітинку B1 на інші клітини, які хочете.

Найкращі інструменти продуктивності офісу

🤖 Kutools AI Aide: Революціонізуйте аналіз даних на основі: Інтелектуальне виконання   |  Згенерувати код  |  Створення спеціальних формул  |  Аналізуйте дані та створюйте діаграми  |  Викликати функції Kutools...
Популярні функції: Знайдіть, виділіть або визначте дублікати   |  Видалити порожні рядки   |  Об’єднайте стовпці або клітинки без втрати даних   |   Раунд без Формули ...
Супер пошук: VLookup за кількома критеріями    Багатозначний VLookup  |   VLookup на кількох аркушах   |   Нечіткий пошук ....
Розширений розкривний список: Швидке створення випадаючого списку   |  Залежний спадний список   |  Виберіть розкривний список, що вибирається ....
Менеджер колонок: Додайте конкретну кількість стовпців  |  Перемістити стовпці  |  Перемкнути статус видимості прихованих стовпців  |  Порівняйте діапазони та стовпці ...
Особливості: Фокус сітки   |  Перегляд дизайну   |   Велика панель формул    Диспетчер робочих книг і аркушів   |  Бібліотека ресурсів (автотекст)   |  Вибір дати   |  Об’єднайте робочі аркуші   |  Шифрування/розшифрування клітинок    Надсилайте листи за списком   |  Супер фільтр   |   Спеціальний фільтр (фільтр жирний/курсив/закреслений...) ...
Топ-15 наборів інструментів12 текст Tools (додати текст, Видалити символи, ...)   |   50 + Графік типи (діаграма Ганта, ...)   |   40+ Практичний Формули (Розрахуйте вік на основі дня народження, ...)   |   19 вставка Tools (Вставте QR-код, Вставити зображення зі шляху, ...)   |   12 Перетворення Tools (Числа до слів, Валютна конверсія, ...)   |   7 Злиття та розділення Tools (Розширені комбіновані ряди, Розділені клітини, ...)   |   ... і більше

Покращуйте свої навички Excel за допомогою Kutools для Excel і відчуйте ефективність, як ніколи раніше. Kutools для Excel пропонує понад 300 додаткових функцій для підвищення продуктивності та економії часу.  Натисніть тут, щоб отримати функцію, яка вам найбільше потрібна...

Опис


Вкладка Office Передає інтерфейс із вкладками в Office і значно полегшує вашу роботу

  • Увімкніть редагування та читання на вкладках у Word, Excel, PowerPoint, Publisher, Access, Visio та Project.
  • Відкривайте та створюйте кілька документів на нових вкладках того самого вікна, а не в нових вікнах.
  • Збільшує вашу продуктивність на 50% та зменшує сотні клацань миші для вас щодня!
Comments (31)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
How would I do this if I am wanting to to apply to the entire workbook with the exception of a few columns. I have columns A:AA and currently have 4,527 rows but more will be added and I will need to make sure the new rows have the same requirement. I need all fields to be requires with the exception of the below.

• Artemis (Column A)
• Host Access Location (Column H)
• Creation Tool (Synthesia) (Column R)
• Search Terms (Column U)
• Notes (Column V)
• eReview SME (column Z)
• Voice Talent (column AA)

Can you please assist in how I can set this up and include any future rows a added?
This comment was minimized by the moderator on the site
How would I do this if I am wanting to to apply to the entire workbook with the exception of a few columns. I have columns A:AA and currently have 4,527 rows but more will be added and I will need to make sure the new rows have the same requirement. I need all fields to be requires with the exception of the below.

• Artemis (Column A)
• Host Access Location (Column H)
• Creation Tool (Synthesia) (Column R)
• Search Terms (Column U)
• Notes (Column V)
• eReview SME (column Z)
• Voice Talent (column AA)

Can you please assist in how I can set this up and include any future rows a added?
This comment was minimized by the moderator on the site
Sorry Sir,

For somebody using VBA for first time, can you please provide some guidance on how to initiate this? I want each row to have same feature I.E. (until one completes all info on row)
This comment was minimized by the moderator on the site
Hi, PM, just follow the steps in this article, then replace the code with the code I provided for you, and then save it. And when you share the workbook to others whose username are different with you, they will be asked to fill every cell in the range (a1:c3, you can change it in the code) until they fill all.
This comment was minimized by the moderator on the site
Thank you so very much, apologies I did not reply back.
This comment was minimized by the moderator on the site
Do mention it. I am glad that can help you.
This comment was minimized by the moderator on the site
Can I email you document so you can best advise me how to implement VBA code so file cannot save if each row is not fully populated? Mine is a bit tricky. Will appreciate the help, been trying for so long.
This comment was minimized by the moderator on the site
Hi, here is a code, it will pops a dialog to remind the user which cell is needed entered, and the workbook cannot be closed and saved until all cells in the range a1:c3 are all filled with contents.
Please modify the script in the code:
1. change the range as you need,
2. change the the user name "Kutools for Excel" in the code to your own username (please make sure other user has no the same user name with you)

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    
    If Application.UserName <> "Kutools for Excel" Then

        Set Rg = Sheets("Sheet2").Range("a1:c3")

        If WorksheetFunction.CountBlank(Rg) > 0 Then

            MsgBox Rg.Parent.Name & " " & Rg.Address & " requires user input", vbInformation, "Kutools for Excel"
            Cancel = True
        End If
    End If

End Sub
This comment was minimized by the moderator on the site
Is het mogelijk om als regel erin te zetten dat als C1 een bepaalde tekst bevat dan D1 ook ingevuld moet worden. Dit moet gelden voor circa 2.000 regels. Het bestand wordt elke keer aangevuld dus het moet alleen gelden voor het aantal regels die nu zijn ingevuld.

Wanneer ik volgende functie erin zet werkt het niet zoals ik wil omdat ik dan meldingen krijg van cellen die nog aangevuld moeten worden en ik wil een tekst als waarde en geen cijfer.

Als Application.WorksheetFunction.CountA(Range("B16:B300")) > 0 then

If Application.WorksheetFunction.CountA(Range("D16:D300")) <> Range("D16:D300").Count Then

MsgBox "Cell D16:D300 vereist gebruikersinvoer", vbInformation, "Kutools for Excel"

Annuleren = Waar

End If

End If

Gr emma
This comment was minimized by the moderator on the site
Is it possible to create a code in a new generated workbook? the scenario is, I will generate a new workbook, and that generated workbook must have a mandatory field to be filled, the user cannot save unless it is not filled the mandatory field. I have already created, generated a new workbook. my problem is, the new generated workbook does not have a code.
This comment was minimized by the moderator on the site
Question, the code worked, but how can choose a range from A7:M7 up to the last row?

and whenever the user will save or close the workbook, the mandatory field have to be filled out
This comment was minimized by the moderator on the site
Hi, Lester, here is a code we modified may help you, change the range A2:F2 to the range as you need.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
'UpdatebyExtend20220916
Dim xRgCount As Integer

Dim xURg As Range

Dim xStr As String

Dim xWSh As Worksheet

Dim xRg, xRg1, xRg2, xRg3 As Range

xStr = "A2:F2"

 

Set xWSh = Application.ActiveSheet

Set xRg = xWSh.Range(xStr)

Set xURg = xWSh.UsedRange

Set xRg1 = xWSh.Cells.Item(xRg.Row + xRg.Rows.Count, 1)

Set xRg2 = xURg.Item(xURg.Count)

Set xRg3 = xWSh.Range(xRg1, xRg2)

Debug.Print xRg3.Address

If (xURg.Row + xURg.Rows.Count - 1) > (xRg.Row + xRg.Rows.Count - 1) Then

   If Application.WorksheetFunction.CountA(xRg3) <> xRg3.Count Then

    MsgBox "There are blank cells under range A2:F2", vbInformation, "Kutools for Excel"

Cancel = True

   End If

End If

End Sub


This comment was minimized by the moderator on the site
Is there a way to make a cells input mandatory before an Active X command button can be used? I have a command button setup to submit a form via email but want to make certain cells mandatory before the button will submit the email.
This comment was minimized by the moderator on the site
Hi, Craig, sorry this problem cannot be solved here, maybe other else can help you.
This comment was minimized by the moderator on the site
i want to make the tick marks mandatory in sheet
This comment was minimized by the moderator on the site
I want to make rows C2 to C7 mandatory and C13 to C19 mandatory?

Any help?

2 sets of ranges are here but under the same column.
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations