What This VBA Code Does
The following VBA code will provide you with a way to delete all shapes from your currently selected spreadsheet. You will also learn how to further manipulate this code to filter out certain shape types from deletion.
VBA Code:
Excluding Certain Shapes
In most cases, you will want to exclude certain shape types from being deleted within your code. Most commonly, you may not want to remove cell comments or charts as (believe it or not) they are considered shapes! You can add an IF statement to test each shape’s type before deleting it in your loop. The following code shows how you can write your VBA:
Below is a table of all the msoShapeType properties that you can use in your IF statement to exclude certain shape types from being deleted. You can use the full name or the enumeration in your code.
Using VBA Code Found On The Internet
Now that you’ve found some VBA code that could potentially solve your Excel automation problem, what do you do with it? If you don’t necessarily want to learn how to code VBA and are just looking for the fastest way to implement this code into your spreadsheet, I wrote an article (with video) that explains how to get the VBA code you’ve found running on your spreadsheet.
Getting Started Automating Excel
Are you new to VBA and not sure where to begin? Check out my quickstart guide to learning VBA. This article won’t overwhelm you with fancy coding jargon, as it provides you with a simplistic and straightforward approach to the basic things I wish I knew when trying to teach myself how to automate tasks in Excel with VBA Macros.
Also, if you haven’t checked out Excel’s latest automation feature called Power Query, I have put together a beginner’s guide for automating with Excel’s Power Query feature as well! This little-known built-in Excel feature allows you to merge and clean data automatically with little to no coding!
How Do I Modify This To Fit My Specific Needs?
Chances are this post did not give you the exact answer you were looking for. We all have different situations and it’s impossible to account for every particular need one might have. That’s why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to get quick answers to complex problems in Excel, PowerPoint, VBA, you name it!
I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee that 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don’t have time to fit everyone’s questions in (there never seem to be quite enough hours in the day!).
I wish you the best of luck and I hope this tutorial gets you heading in the right direction!
Chris
Founder, TheSpreadsheetGuru.com
I have an excel worksheet where a macro tied to a button draws dynamic shapes based on the user input parameters in the worksheet.
I am trying to write a new macro to clean the sheet, or in other words delete all shapes in the worksheet.
I tried using the code below, and it indeed deletes all shapes, however button form controls also get deleted in the process. Is there an easy way to only get rid of the shapes (arrows, textboxes, ellipses etc.) in the worksheet? Thanks a bunch!!!
Sub DeleteAllShapes()
Dim Shp As Shape
For Each Shp In ActiveSheet.Shapes
Shp.Delete
Next Shp
End Sub
asked Oct 8, 2012 at 21:08
To delete autoshapes and textboxes only you can use:
Sub DeleteAllShapes()
Dim Shp As Shape
For Each Shp In ActiveSheet.Shapes
If Shp.Type = msoAutoShape Or Shp.Type = msoTextBox Then Shp.Delete
Next Shp
End Sub
Alternatively you can work the other way around and specify the types not to delete. You can use the enumerated types but it’s more readable to use the type names. The following snippet will delete everything apart from Form Controls and OLE control objects.
Sub DeleteAllShapes()
Dim Shp As Shape
For Each Shp In ActiveSheet.Shapes
If Not (Shp.Type = msoOLEControlObject Or Shp.Type = msoFormControl) Then Shp.Delete
Next Shp
End Sub
A full list of MSO Shape Types.
http://msdn.microsoft.com/en-us/library/office/aa432678(v=office.12).aspx
Ron de Bruin has a good collection of snippets which may be relevant to anyone else coming across this question.
http://www.rondebruin.nl/controlsobjectsworksheet.htm
answered Oct 8, 2012 at 21:42
Jamie BullJamie Bull
12.7k14 gold badges76 silver badges116 bronze badges
5
It sounds like you just want to delete drawing objects.
Building on Jamie Bull’s excellent advice, firstly here’s the updated link to the relevant page in Ron de Bruin’s website:
Delete or Hide Objects/Controls on a worksheet
and secondly, you may find that this single line will do the trick:
ActiveSheet.DrawingObjects.Delete
answered Aug 24, 2022 at 15:43
LondonJustinLondonJustin
731 gold badge1 silver badge7 bronze badges
0 / 0 / 0 Регистрация: 08.04.2012 Сообщений: 3 |
|
1 |
|
Удаление фигур с листа08.04.2012, 18:05. Показов 10262. Ответов 4
На листе с помощью готовых фигур — «прямая соединительная линия» нарисована «Z». Как удалить эту «Z». Сломал весь мозг.
0 |
15136 / 6410 / 1730 Регистрация: 24.09.2011 Сообщений: 9,999 |
|
08.04.2012, 18:15 |
2 |
F5 — выделить — объекты — ОК — Del. Если лист защищен, перед этим надо снять защиту.
2 |
Big BOSs 0 / 0 / 0 Регистрация: 08.04.2012 Сообщений: 3 |
||||
12.04.2012, 19:14 [ТС] |
3 |
|||
Спасибо за помощь (извиняюсь что так долго, просто не было времени), но при использовании кода VBA:
удаляются все фигуры с листа даже кнопки (ComandButton). Блин, я уже задолбалс
0 |
KoGG 5590 / 1580 / 406 Регистрация: 23.12.2010 Сообщений: 2,366 Записей в блоге: 1 |
||||
16.04.2012, 17:38 |
4 |
|||
2 |
0 / 0 / 0 Регистрация: 08.04.2012 Сообщений: 3 |
|
16.04.2012, 19:42 [ТС] |
5 |
Ура!!!!!!! Заработало!!!!!!!! Огромный фенкс
0 |
Содержание
- VBA Vault
- VBA To Delete All Shapes On A Spreadsheet
- What This VBA Code Does
- VBA Code:
- Excluding Certain Shapes
- Using VBA Code Found On The Internet
- Getting Started Automating Excel
- How Do I Modify This To Fit My Specific Needs?
- Remove all shapes from excel
- Как быстро удалить все автофигуры в Excel?
- Удалите все автофигуры на активном листе с помощью функции Перейти в Excel
- Удалите все автофигуры на активном листе с помощью VBA
- Удалите все автофигуры на листе или в книге с помощью Kutools for Excel
- Use Excel VBA Command to delete all shapes excluding specific ShapeTypes
- 1 Answer 1
- Remove all shapes from excel
- Answered by:
- Question
- Answers
- All replies
VBA Vault
An Excel, PowerPoint, & MS Word blog providing handy and creative VBA code snippets. These macro codes are well commented and are completely functional when copied into a module.
VBA To Delete All Shapes On A Spreadsheet
What This VBA Code Does
The following VBA code will provide you with a way to delete all shapes from your currently selected spreadsheet. You will also learn how to further manipulate this code to filter out certain shape types from deletion.
VBA Code:
Sub DeleteAllShapes()
‘PURPOSE: Remove All Shape Objects From The Active Worksheet
‘SOURCE: www.TheSpreadsheetGuru.com/the-code-vault
Dim shp As Shape
For Each shp In ActiveSheet.Shapes
shp.Delete
Next shp
Excluding Certain Shapes
In most cases, you will want to exclude certain shape types from being deleted within your code. Most commonly, you may not want to remove cell comments or charts as (believe it or not) they are considered shapes! You can add an IF statement to test each shape’s type before deleting it in your loop. The following code shows how you can write your VBA:
Sub DeleteAllShapes()
‘PURPOSE: Remove All Shape Objects From The Active Worksheet (Excludes Charts/Comments)
‘SOURCE: www.TheSpreadsheetGuru.com/the-code-vault
Dim shp As Shape
For Each shp In ActiveSheet.Shapes
If shp.Type <> msoChart And shp.Type <> msoComment Then shp.Delete
Next shp
Below is a table of all the msoShapeType properties that you can use in your IF statement to exclude certain shape types from being deleted. You can use the full name or the enumeration in your code.
Name | Enum | Type |
---|---|---|
msoAutoShape | 1 | AutoShape |
msoCallout | 2 | Callout |
msoCanvas | 20 | Canvas |
msoChart | 3 | Chart |
msoComment | 4 | Comment |
msoContentApp | 27 | Content Office Add-in |
msoDiagram | 21 | Diagram |
msoEmbeddedOLEObject | 7 | Embedded OLE object |
msoFormControl | 8 | Form Control |
msoFreeform | 5 | Freeform |
msoGraphic | 28 | Graphic |
msoGroup | 6 | Group |
msoIgxGraphic | 24 | SmartArt Graphic |
msoInk | 22 | Ink |
msoInkComment | 23 | Ink Comment |
msoLine | 9 | Line |
msoLinkedGraphic | 29 | Linked Graphic |
msoLinkedOLEObject | 10 | Linked OLE object |
msoLinkedPicture | 11 | Linked Picture |
msoMedia | 16 | Media |
msoOLEControlObject | 12 | OLE Control Object |
msoPicture | 13 | Picture |
msoPlaceholder | 14 | Placeholder |
msoScriptAnchor | 18 | Script Anchor |
msoShapeTypeMixed | -2 | Mixed Shape Type |
msoTable | 19 | Table |
msoTextBox | 17 | Text Box |
msoTextEffect | 15 | Text Effect |
msoWebVideo | 26 | Web Video |
Using VBA Code Found On The Internet
Now that you’ve found some VBA code that could potentially solve your Excel automation problem, what do you do with it? If you don’t necessarily want to learn how to code VBA and are just looking for the fastest way to implement this code into your spreadsheet, I wrote an article (with video) that explains how to get the VBA code you’ve found running on your spreadsheet.
Getting Started Automating Excel
Are you new to VBA and not sure where to begin? Check out my quickstart guide to learning VBA. This article won’t overwhelm you with fancy coding jargon, as it provides you with a simplistic and straightforward approach to the basic things I wish I knew when trying to teach myself how to automate tasks in Excel with VBA Macros.
Also, if you haven’t checked out Excel’s latest automation feature called Power Query, I have put together a beginner’s guide for automating with Excel’s Power Query feature as well! This little-known built-in Excel feature allows you to merge and clean data automatically with little to no coding!
How Do I Modify This To Fit My Specific Needs?
Chances are this post did not give you the exact answer you were looking for. We all have different situations and it’s impossible to account for every particular need one might have. That’s why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to get quick answers to complex problems in Excel, PowerPoint, VBA, you name it!
I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee that 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don’t have time to fit everyone’s questions in (there never seem to be quite enough hours in the day!).
I wish you the best of luck and I hope this tutorial gets you heading in the right direction!
Источник
Remove all shapes from excel
Как быстро удалить все автофигуры в Excel?
Если вы хотите избавиться от автоматических форм в Excel, вы можете найти простой способ быстро удалить все формы, а не удалять автоматические формы по одной. Следующий хитрый метод поможет вам удалить все автофигуры одним щелчком мыши.
Удалите все автофигуры на активном листе с помощью функции Перейти в Excel
Удивительный! Использование эффективных вкладок в Excel, таких как Chrome, Firefox и Safari!
Экономьте 50% своего времени и сокращайте тысячи щелчков мышью каждый день!
Если есть только один вид объектов — автофигуры на листе, вы можете удалить все автофигуры с помощью Перейти к функции.
1. Нажмите F5 or Ctrl + G для отображения Перейти к диалоговое окно и щелкните Особый.., см. снимок экрана:
2. Проверьте Объекты, А затем нажмите Ok, он выберет все объекты, см. снимок экрана:
3. Затем нажмите Возврат на одну позицию кнопку, чтобы удалить все автофигуры.
Внимание: Объекты содержат автофигуры, изображения, картинки и т. Д. Применение этого метода приведет к удалению других объектов, кроме автофигур, если на листе есть не только объект автофигур.
Удалите все автофигуры на активном листе с помощью VBA
Использование макроса VBA может помочь вам быстро удалить все автоматические формы на активном листе.
Шаг 1: Удерживайте ALT + F11 ключи, и он открывает Microsoft Visual Basic для приложений окно.
Шаг 2: нажмите Вставить > Модули, и вставьте следующий макрос в Модули окно.
VBA: удалить все фигуры на активном листе.
Sub DeleteShapes ()
Дим Шп как форма
Для каждой детали в ActiveSheet.Shapes
Шп.Удалить
Следующая Шп
End Sub
Шаг 3: нажмите F5 ключ для запуска этого макроса.
Затем вы увидите, что все фигуры на активном листе быстро удаляются.
Заметки:
1. Этот макрос VBA может удалять только все фигуры на активном листе.
2. Этот макрос VBA может удалять все виды фигур на активном листе, включая изображения, клипы, фигуры, SmartArt, диаграммы, текстовые поля и т. Д.
Удалите все автофигуры на листе или в книге с помощью Kutools for Excel
Если вы хотите удалить только автоматические формы с листа, Kutools for Excel‘s Удалить иллюстрации и объект может помочь вам удалить определенные фигуры на активном листе, выбранных листах или всей книге одним щелчком мыши.
Kutools for Excel включает более 300 удобных инструментов Excel. Бесплатная пробная версия без ограничений в течение 30 дней. Получить сейчас.
Шаг 1: нажмите Кутулс > Удалить иллюстрации и объект.
Шаг 2: В Удалить инструменты диалоговое окно, пожалуйста, отметьте Авто формы вариант и отметьте один из вариантов в заглянуть раздел. См. Следующий снимок экрана:
- Если вы установите флажок Активный лист опция, он удалит все автоматические формы на активном листе;
- Если вы установите флажок Выбранные листы опция, он удалит все автоматические формы на выбранных листах;
- Если вы установите флажок Все листы вариант, он удалит все автоматические формы во всей книге.
Шаг 3: нажмите OK, он удалит все автоматические формы.
Kutools for Excel’s Удалить инструменты может помочь нам удалить все диаграммы, линии, изображения, автофигуры, умные рисунки, текстовые поля, связанные объекты OLE и встроенные объекты OLE на активном листе, выбранном листе или на всех листах текущей книги. Нажмите, чтобы узнать больше…
Источник
Use Excel VBA Command to delete all shapes excluding specific ShapeTypes
I have part drawings that I mark up with welds. Each drawing is the same but has unique serial numbers. Each weld is represented by a Circle Shape (msoShapeOval). After I hit my save function, I want all Circle Shapes (and ONLY circle shapes) removed from the drawing so that I can begin the next serial number.
I tried If statements with Shape.Type commands to delete all msoShapeOval, but the file doesn’t recognize the shapes.
I also tried the opposite where If Not (textbox, OLE, picture, etc) delete shape, however that deleted ALL shapes.
This is the CommandButton which calls the DeleteWelds sub
Finally the Sub which creates the Oval shapes to begin with.
The method where I only delete msoShapeOval doesn’t delete any objects, but when I use If not (mso(insert ones I need)) all objects are deleted.
1 Answer 1
You need to use shp.AutoShapeType instead of shp.Type as commented by @AhmedAU in the comments (The comment is now deleted).
There are different kinds of shapes in Excel. For example 3D model , AutoShape , Callout etc. You can get the entire list in MsoShapeType enumeration (Office)
So when you say Shape.Type , then it refers to MsoShapeType . Let’s take an example. Insert these shapes in the worksheet
Now run this code
You will get this output
So you will notice that Oval 1 , Right Arrow 5 and Explosion 1 6 have a shape type of 1 . This means (if you refer to the above link) these are AutoShapes
Источник
Remove all shapes from excel
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
I’m trying to delete all shapes in the active sheet. I’d like to select all shapes and delete them, but I am unable to determine what type of object comes back from Selection in this scenario:
I am able to delete them one by one, but this is less efficient. Can anyone tell me the object type that «selection» will be?
Answers
One possibility would be to assign all the Shapes on the sheet to a ShapeRange. The ShapeRange object has a delete method.
Another would be something like this
Excel.Worksheet sht;
sht = xlApp.ActiveSheet;
sht.Shapes.SelectAll;
xlApp.Selection.Delete();
Excel has a TypeName method that will return this information. The VBA syntax:
I’m using C#, not VBA, and can’t find the TypeName option. When I use Application.Selection.GetType(), it turns out to be a COM object, which doesn’t give me much type information.
The only reason I’m interested in the type of the current Selection is to be able to delete all shapes at once — is there another mechansim to do this?
Источник
Если вы хотите избавиться от автоматических форм в Excel, вы можете найти простой способ быстро удалить все формы, а не удалять автоматические формы по одной. Следующий хитрый метод поможет вам удалить все автофигуры одним щелчком мыши.
- Удалите все автофигуры на активном листе с помощью функции Перейти в Excel
- Удалите все автофигуры на активном листе с помощью VBA
- Удалите все автофигуры на листе или в книге с помощью Kutools for Excel
Удалите все автофигуры на активном листе с помощью функции Перейти в Excel
Если есть только один вид объектов — автофигуры на листе, вы можете удалить все автофигуры с помощью Перейти к функции.
1. Нажмите F5 or Ctrl + G для отображения Перейти к диалоговое окно и щелкните Особый.., см. снимок экрана:
2. Проверьте Объекты, А затем нажмите Ok, он выберет все объекты, см. снимок экрана:
3. Затем нажмите Возврат на одну позицию кнопку, чтобы удалить все автофигуры.
Внимание: Объекты содержат автофигуры, изображения, картинки и т. Д. Применение этого метода приведет к удалению других объектов, кроме автофигур, если на листе есть не только объект автофигур.
Удалите все автофигуры на активном листе с помощью VBA
Использование макроса VBA может помочь вам быстро удалить все автоматические формы на активном листе.
Шаг 1: Удерживайте ALT + F11 ключи, и он открывает Microsoft Visual Basic для приложений окно.
Шаг 2: нажмите Вставить > Модули, и вставьте следующий макрос в Модули окно.
VBA: удалить все фигуры на активном листе.
Sub DeleteShapes ()
Дим Шп как форма
Для каждой детали в ActiveSheet.Shapes
Шп.Удалить
Следующая Шп
End Sub
Шаг 3: нажмите F5 ключ для запуска этого макроса.
Затем вы увидите, что все фигуры на активном листе быстро удаляются.
Заметки:
1. Этот макрос VBA может удалять только все фигуры на активном листе.
2. Этот макрос VBA может удалять все виды фигур на активном листе, включая изображения, клипы, фигуры, SmartArt, диаграммы, текстовые поля и т. Д.
Удалите все автофигуры на листе или в книге с помощью Kutools for Excel
Если вы хотите удалить только автоматические формы с листа, Kutools for Excel‘s Удалить иллюстрации и объект может помочь вам удалить определенные фигуры на активном листе, выбранных листах или всей книге одним щелчком мыши.
Kutools for Excel включает более 300 удобных инструментов Excel. Бесплатная пробная версия без ограничений в течение 30 дней. Получить сейчас.
Шаг 1: нажмите Кутулс > Удалить иллюстрации и объект.
Шаг 2: В Удалить инструменты диалоговое окно, пожалуйста, отметьте Авто формы вариант и отметьте один из вариантов в заглянуть раздел. См. Следующий снимок экрана:
- Если вы установите флажок Активный лист опция, он удалит все автоматические формы на активном листе;
- Если вы установите флажок Выбранные листы опция, он удалит все автоматические формы на выбранных листах;
- Если вы установите флажок Все листы вариант, он удалит все автоматические формы во всей книге.
Шаг 3: нажмите OK, он удалит все автоматические формы.
Kutools for Excel’s Удалить инструменты может помочь нам удалить все диаграммы, линии, изображения, автофигуры, умные рисунки, текстовые поля, связанные объекты OLE и встроенные объекты OLE на активном листе, выбранном листе или на всех листах текущей книги. Нажмите, чтобы узнать больше…
Относительные статьи:
- Легко удалить все изображения
- Удалить все диаграммы Рабочие книги
- Быстро удалить все текстовые поля
Лучшие инструменты для работы в офисе
Kutools for Excel Решит большинство ваших проблем и повысит вашу производительность на 80%
- Снова использовать: Быстро вставить сложные формулы, диаграммы и все, что вы использовали раньше; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма …
- Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон…
- Объединить ячейки / строки / столбцы без потери данных; Разделить содержимое ячеек; Объединить повторяющиеся строки / столбцы… Предотвращение дублирования ячеек; Сравнить диапазоны…
- Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор …
- Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое …
- Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии…
- Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом …
- Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF…
- Более 300 мощных функций. Поддерживает Office/Excel 2007-2021 и 365. Поддерживает все языки. Простое развертывание на вашем предприятии или в организации. Полнофункциональная 30-дневная бесплатная пробная версия. 60-дневная гарантия возврата денег.
Вкладка Office: интерфейс с вкладками в Office и упрощение работы
- Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
- Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
- Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!