Перейти к основному содержанию

 Как применить кнопку для очистки определенных ячеек в Excel?

Обычно вы можете удерживать Ctrl нажмите клавишу, чтобы выбрать несколько конкретных ячеек, а затем очистите содержимое ячейки по мере необходимости. Если вам всегда нужно время от времени очищать эти конкретные ячейки, вы можете создать кнопку очистки, чтобы очистить их одним щелчком мыши. В этой статье я расскажу о том, как создать кнопку «Очистить все», чтобы очистить определенное содержимое ячеек.

Применить кнопку, чтобы очистить конкретное содержимое ячейки с помощью кода VBA


стрелка синий правый пузырь Применить кнопку, чтобы очистить конкретное содержимое ячейки с помощью кода VBA

Сначала вы должны создать кнопку формы, а затем применить код, наконец, привязать код к кнопке формы. Пожалуйста, сделайте следующее:

1. Нажмите Вставить > Формы > Прямоугольники , чтобы выбрать форму прямоугольника, а затем перетащите мышь, чтобы нарисовать кнопку прямоугольника в любом месте листа, как вам нужно, см. снимок экрана:

кнопка doc очистить ячейки 1

2. Затем введите текст и отформатируйте кнопку формы, как вам нужно, см. Снимок экрана:

кнопка doc очистить ячейки 2

3. Затем вы должны вставить код VBA, удерживая ALT + F11 , чтобы открыть Microsoft Visual Basic для приложений окно. Нажмите Вставить > Модулии вставьте следующий код в Модули Окно.

Код VBA: очистить содержимое определенных ячеек:

Sub Clearcells()
'Updateby Extendoffice
Range("A2", "A5").Clear
Range("C10", "D18").Clear
Range("B8", "B12").Clear
End Sub

Внимание: В приведенном выше коде: A2, A5 указать, что он очистит ячейки в диапазоне A2: A5, а не только две ячейки по отдельности, вы можете добавить несколько диапазонов, например Диапазон («B8», «B12»). Очистить сценарий внутри кода, чтобы очистить.

4. Затем сохраните и закройте окно кода, а затем свяжите код с кнопкой формы, щелкните кнопку правой кнопкой мыши и выберите Назначить макрос, В Назначить макрос диалогового окна, выберите Клирселлс кодовое имя из Имя макроса список и щелкните OK кнопку, чтобы выйти из этого диалогового окна. Смотрите скриншот:

кнопка doc очистить ячейки 3

5. А теперь, когда вы нажимаете Очистить все Кнопка, определенные вами ячейки очищаются сразу, см. снимок экрана:

кнопка doc очистить ячейки 4

Лучшие инструменты для офисной работы

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

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

вкладка kte 201905


Office Tab Добавляет в Office интерфейс с вкладками и значительно упрощает вашу работу

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!
Comments (65)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
I wanted that the confirmation needed for clear button .....so that the data is not cleared by mistakenly press the "clear" tab

And i wanted to say thanks for your brilliant work....thanks a lot in advance....

wish you have a great day...
This comment was minimized by the moderator on the site
Hello,
I am using this on one spreadsheet, but on 3 separate tabs. Everything was working last time I had the workbook open but today it is giving me an error "Ambiguous name detected: Clearcells". Please help!
This comment was minimized by the moderator on the site
Hallo zusammen,
hab soweit alles gemacht zu gewiesen usw. Funktioniert auch aber sobald ich die Datei öffne funktioniert es nicht mehr und muss alles neu eingeben.

Vorab vielen Dank
This comment was minimized by the moderator on the site
Meinte, nach dem schließen und dann wieder öffne.
This comment was minimized by the moderator on the site
Hi. I am trying to use a toggle button to clear all cells of color and text, but only the cells that contain the word “event”. And then I’d like to use the same toggle button to add the color and the word “event” back onto the spreadsheet. Can this be done?
This comment was minimized by the moderator on the site
Hallo,

Hoe kan ik cellen in een range met een formule intact houden met bovenstaand script?

Mvg,

Nol
This comment was minimized by the moderator on the site
Hello, Nol,
Do you mean to keep the formula cells when clearing the cell contents? Could you explain your problem by using English?

Thank you!
This comment was minimized by the moderator on the site
Hi Skyyang,

Thats what I mean indeed

Regards,

Nol
This comment was minimized by the moderator on the site
Hi, Nol,,
Maybe the follwoing VBA code can help you:
Sub Clearcells()
Dim xStr As String
Dim xRgs, xRg, xRgA As Range
xStr = "A2:C3,A5:E16,F5:H10"
Set xRgs = Range(xStr)
For Each xRgA In xRgs.Areas
    For Each xRg In xRgA
        If Not xRg.HasFormula Then
            xRg.Clear
        End If
    Next
Next
End Sub


Please change the cell references to your need, and you should use the comma to separate the data range.
Please have a try, hope it can help you!
This comment was minimized by the moderator on the site
Thanks Skyyang, the script works like an charm! Keep up the good work
This comment was minimized by the moderator on the site
Can you help me find a code that would clear the contents of merged cells but keep the formatting as well as formulas?
Thank you
This comment was minimized by the moderator on the site
¡Hola! Este código es fantástico para mí: Sub Clearcells() Rango("A2", "A5").ClearContents Rango("C10", "D18").ClearContents Rango("B8", "B12").ClearContents End Sub
Sin embargo, quisiera que me indicarais, si sois tan amables, cómo puedo a la vez que borro el contenido de dichas celdas, que éstas no tuvieran ningún color de relleno, el estilo fuera el normal, sin negrita ni cursiva y la fuente fuera arial 10 . Muchísimas gracias de antemano!!
This comment was minimized by the moderator on the site
Bonjour, j'ai créé un classeur pour une compétition sportive, 2 feuilles, une pour les éliminatoires et une pour les parties finales, j'ai créé un bouton par feuilles pour effacer le contenu des cellules, je voudrais protéger ces boutons, ils ne doivent être utilisés qu'à la fin de la compétition.
Merci d'avance
Didier
This comment was minimized by the moderator on the site
Hello Didier,

How are you. You can create two buttons for the two worksheets, each button for each worksheet. Then you can save the workbook. You can decide which contents to be cleared in which worksheets. Have a nice day.

Sincerely,
Mandy
This comment was minimized by the moderator on the site
Many thanks Super ! 
This comment was minimized by the moderator on the site
Hi, this works great. However, my macro-enabled excel file is loading too slowly. It took 6-7 seconds to clear the contents. If I manually clear them, took me 2 seconds. Is it because the clearing area is too large? Column B through Q, from row 2 to 9000. Can you help me to fix the speed issue?
This comment was minimized by the moderator on the site
Hello Trang,Glad to help. I just tried the VBA code to clear data from Column B through T, from row 1 to over 10000. It took less than 1 second to complete the process. Therefore, I guess it's not because the clearing area too large. And the VBA code is too simple to be the blame. I guess maybe the problem is your computer storage limit. Try not to open too many files or run too many programs at the same time. Please have a try. Have a nice day.Sincerely,Mandy
This comment was minimized by the moderator on the site
I'm trying to delete content in an individual cell but in multiple cells as I go along my To do list. I know this is possible as I've used it before I just done know how to set it up.
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