Excel vba удалить shape

Программное удаление элементов управления формы с рабочего листа при помощи кода VBA Excel. Метод Delete объекта Shape — синтаксис, примеры.

Метод Delete объекта Shape

Синтаксис метода Delete объекта Shape:

Workbooks("BookName").Worksheets("SheetName").Shapes("ShapeName").Delete

  • BookName – имя рабочей книги вместе с расширением, книга должна быть открыта.
  • SheetName – имя рабочего листа, которое отображается на ярлычке.
  • ShapeName – имя элемента управления формы.

Элементы управления формы имеют два имени: основное на английском языке и альтернативное на русском. Как ни странно, оба этих имени можно использовать в качестве ShapeName в выражении, удаляющем элемент управления с рабочего листа.

Чтобы узнать альтернативное имя на русском языке, необходимо кликнуть правой кнопкой мыши по элементу управления формы. Откроется первое контекстное меню, а в адресной строке отобразится альтернативное имя.

Альтернативное имя кнопки на русском языке

Альтернативное имя кнопки на русском языке

Чтобы узнать основное имя на английском языке, необходимо кликнуть правой кнопкой мыши по элементу управления формы с задержкой на одну секунду: нажать кнопку, подождать одну секунду и отпустить. Откроется второе контекстное меню, а в адресной строке отобразится основное имя.

Основное имя кнопки на английском языке

Основное имя кнопки на английском языке

Точно так же определяются основные и альтернативные имена других элементов управления формы.

Удаление одного элемента управления

Удаление элемента управления формы с рабочего листа книги, в которой размещен код:

ThisWorkbook.Worksheets("Лист2").Shapes("Button 5").Delete

Worksheets("Лист4").Shapes("Перекл. 3").Delete

ActiveSheet.Shapes("Drop Down 2").Delete

Удаление элемента управления формы с рабочего листа другой открытой книги:

Workbooks("Чеки.xls").Worksheets("Чек №5").Shapes("Кнопка 2").Delete

Удаление всех элементов управления

Удаление всех элементов управления формы всех типов:

Sub Primer_1()

Dim myShap As Shape

  For Each myShap In ActiveSheet.Shapes

    myShap.Delete

  Next

End Sub

Этот код удалит все имеющиеся на листе элементы управления формы.

Удаление всех однотипных элементов управления формы:

Sub Primer_2()

Dim myShap As Shape

  For Each myShap In ThisWorkbook.ActiveSheet.Shapes

    If myShap.Name Like «Button*» Then myShap.Delete

  Next

End Sub

Этот код удалит все имеющиеся на листе элементы, в наименование которых входит подстрока «Button». В данном случае будут удалены все кнопки.

Точно также можно удалить и другие типы элементов управления формы, заменив аргумент оператора Like «Button*» на часть имени другого типа элементов с символом звездочки. Например: «Label*», «Drop Down*», «Check Box*» и т.д.

Смотрите как удалить элементы управления ActiveX с рабочего листа.

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

Community's user avatar

asked Oct 8, 2012 at 21:08

marillion's user avatar

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 Bull's user avatar

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

LondonJustin's user avatar

LondonJustinLondonJustin

731 gold badge1 silver badge7 bronze badges

Содержание

  1. VBA Vault
  2. VBA To Delete All Shapes On A Spreadsheet
  3. What This VBA Code Does
  4. VBA Code:
  5. Excluding Certain Shapes
  6. Using VBA Code Found On The Internet
  7. Getting Started Automating Excel
  8. How Do I Modify This To Fit My Specific Needs?
  9. Remove all shapes from excel
  10. Как быстро удалить все автофигуры в Excel?
  11. Удалите все автофигуры на активном листе с помощью функции Перейти в Excel
  12. Удалите все автофигуры на активном листе с помощью VBA
  13. Удалите все автофигуры на листе или в книге с помощью Kutools for Excel
  14. Use Excel VBA Command to delete all shapes excluding specific ShapeTypes
  15. 1 Answer 1
  16. Remove all shapes from excel
  17. Answered by:
  18. Question
  19. Answers
  20. 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?

Источник

VBA Code To Delete All Shapes On A Excel sheet

Complete Excel VBA Course

Here is a VBA code which deletes all the shapes from an Excel sheet. Code is simple but you have to be bit careful while using this code as it deletes all the Shapes, Smart Shapes, Charts, Pictures, Objects and Equations from the sheet

VBA Code to delete all shapes in excel sheet

'Following function deletes all the Shapes, Smart Shapes, Charts,
'Pictures, Objects and Equations from the Excel worksheet
Sub DeleteShapesFromSheet()
    'Declare variable
    Dim objShape As Shape
    'Loop through all the shapes from sheet1 and delete
    For Each objShape In Sheet1.Shapes
        objShape.Delete
    Next
End Sub

VBA Code to delete all shapes on a excel sheet follow below steps:

1. Open an Excel file
2. Press Alt+F11
3. Insert a Module (Insert>Module) from menu bar
4. Paste the code in the module
5. Click on ‘View Macros’ option available under View>Macros ribbon

Delete Shapes in Excel through VBA

6. Select ‘DeleteShapesFromSheet’ and click on Run

Complete Excel VBA Course

Delete Shapes in Excel through VBA

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.TheExcelsirji.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

End Sub

Download Practice File

You can also practice this through our practice files. Click on the below link to download the practice file.

Recommended Articles

  • Time and Motion study- complete guide
  • VBA to read Excel Data using a connection string
  • Lock cells to avoid editing, Hide formulas
  • Excel VBA Tool to get File Properties
  • How to hide sheets in Excel with or without VBA?

Excel VBA Course : Beginners to Advanced

We are currently offering our Excel VBA Course at discounted prices. This courses includes On Demand Videos, Practice Assignments, Q&A Support from our Experts. Also after successfully completion of the certification, will share the success with Certificate of Completion

This course is going to help you to excel your skills in Excel VBA with our real time case studies.

Lets get connected and start learning now. Click here to Enroll.

Secrets of Excel Data Visualization: Beginners to Advanced Course

Here is another best rated Excel Charts and Graph Course from excelsirji. This courses also includes On Demand Videos, Practice Assignments, Q&A Support from our Experts.

This Course will enable you to become Excel Data Visualization Expert as it consists many charts preparation method which you will not find over the internet.

So Enroll now to become expert in Excel Data Visualization. Click here to Enroll.

Excel, just like other Office products, supports AutoShapes. Although Excel shapes are nice to have for presentation purposes, getting rid of them may become time consuming if your workbook is cluttered with them. This article shows you how to delete Excel shapes (AutoShapes) automatically using VBA.

How to delete Excel shapes (AutoShapes) using VBA

AutoShapes are stored in the Shapes collection under a worksheet object. This means that we can loop through Excel shapes in a worksheet and delete them.

    For Each shp In ActiveSheet.Shapes
        shp.Delete
    Next shp

To delete the AutoShapes from the whole workbook, we need to check every sheet.

    For Each ws In ActiveWorkbook.Worksheets
        For Each shp In ws.Shapes
            shp.Delete
        Next shp
    Next ws

You can use codes in two ways:

  • Module
  • Immediate Window

In the Module method, you need to add the module into the workbook or the add-in file. Copy and paste the code into the module to run it. The main advantage of the module method is that it allows saving the code in the file, so that it can be used again later. Furthermore, the subroutines in modules can be used by icons in the menu ribbons or keyboard shortcuts. Remember to save your file in either XLSM or XLAM format to save your VBA code.

The Immediate Window method, on the other hand, is essentially a quick and dirty method where you can simply copy and paste the code into the Immediate Window and press the Enter key to run it. Unfortunately, any code you use in the Immediate Window will not be saved. Also note that icons and keyboard shortcuts will not be available.

Delete AutoShapes in an active sheet

Module method:

Sub DeleteShapesInActiveWorksheet()
    Dim shp As Shape
    For Each shp In ActiveSheet.Shapes
        shp.Delete
    Next shp
End Sub

Immediate Window method:

For Each shp In ActiveSheet.Shapes: shp.Delete: Next shp

Delete AutoShapes in a workbook

Module method:

Sub DeleteShapesInActiveWorkbook()
    Dim ws As Worksheet
    Dim shp As Shape
    For Each ws In ActiveWorkbook.Worksheets
        For Each shp In ws.Shapes
            shp.Delete
        Next shp
    Next ws
End Sub

Immediate Window method:

For Each ws In ActiveWorkbook.Worksheets: For Each shp In ws.Shapes: shp.Delete: Next shp: Next ws
 

hellm

Пользователь

Сообщений: 107
Регистрация: 23.12.2014

Как удалить с помощью макроса геометрическую фигуру? Записью получается, что их там массив. Но если я создал х таких фигур, откуда я узнаю, какую мне удалять? Записи я оставил во втором модуле.

Прикрепленные файлы

  • 123.xlsm (18.42 КБ)

 

RAN

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

#2

17.11.2017 12:49:36

Цитата
hellm написал:
откуда я узнаю, какую мне удалять?

Это вы у нас спрашиваете?

 

hellm

Пользователь

Сообщений: 107
Регистрация: 23.12.2014

Ну да.
Вот, переформулировал.
Как выглядит универсальный макрос, удаляющий фигуру? Когда записываю, в коде появляется номер, похожий на порядковый (всегда разный). Я записал несколько таких, чтоб разобраться (фигуры удалил, понятно дело).

 

The_Prist

Пользователь

Сообщений: 14181
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

Универсального макроса нет. Нужен хоть какой-то признак: это либо выделенная фигура, либо первая добавленная на лист, либо последняя. Для начала надо именно с этим определиться. А удалить вообще проблем не составляет.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

hellm

Пользователь

Сообщений: 107
Регистрация: 23.12.2014

#5

17.11.2017 13:24:50

Цитата
The_Prist написал:
Нужен хоть какой-то признак

На странице будет 4 прямоугольника. Их надо мочь поочередно включить/выключить(создать/удалить). Первая/последняя отпадает. Порядок создания фигур всегда разный. Может, выделенная? Так я ее и без макроса удалю. Как быть? Как удалять фигуру макросом?

 

The_Prist

Пользователь

Сообщений: 14181
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

Перед Вами четыре одинаковых яблока. Ядовитое только одно. Как убрать только его, если мы не знаем как отличить от съедобных, и при этом не отравиться самому и не отравить других? Сейчас именно так задача Ваша звучит.
Если Вы не знаете какую фигуру удалять и какие есть вообще признаки для определения нужной — как мы-то это сможешь определить? Вы сами понимаете абсурдность ситуации? Если надо удалить — значит должна быть причина. Если есть причина — значит есть какое-то действие, предшествующее причине. А значит можно попытаться определить признак для удаления. Сосредоточьтесь на этом. Без этого Ваша задача не имеет решения.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

hellm

Пользователь

Сообщений: 107
Регистрация: 23.12.2014

Мы будем просвечивать яблоко рентгеном!  :D

Что, если просто выключать? Менять цвет на прозрачный? Удалять их в обычном понимании этого слова не обязательно. У них ведь есть номер, как я понял из процедуры удаления. Так этим номером и можно воспользоваться! Он будет всегда статичный.

Изменено: hellm17.11.2017 13:32:47

 

The_Prist

Пользователь

Сообщений: 14181
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#8

17.11.2017 13:37:09

Цитата
hellm написал:
Что, если просто выключать?

Давайте еще раз. А что выключать-то будем? Вообще без разницы — выключать или удалять. Надо просто знать как определить ту фигуру, которую отключить или удалить. Это либо текст на фигуре, либо тип, либо цвет, либо еще что-то. Вы когда наконец это поймете-то? Нельзя удалить фигуру, не зная её индекса или имени. Индексы зависят от порядка добавления фигур на лист, имена вообще отдельная тема.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

hellm

Пользователь

Сообщений: 107
Регистрация: 23.12.2014

#9

17.11.2017 13:48:23

Цитата
The_Prist написал: имена вообще отдельная тема

Так может по именам? Их там 4 штуки. Менять цвет на прозрачный.
Если по именам сложнее, чем по индексу, тогда по индексу.
Это и будет их определитель.

 

The_Prist

Пользователь

Сообщений: 14181
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#10

17.11.2017 14:12:24

Код
Shapes("Имя Фигуры").Delete
Shapes(2).Delete

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

hellm

Пользователь

Сообщений: 107
Регистрация: 23.12.2014

#11

17.11.2017 17:01:05

То, что доктор прописал! Спасибо большое. Буду имплементировать.

Hi, Excellers welcome to another #MacroMonday blog. Today I want to share with you how to quickly delete any shapes that you have in your Excel workbook. Ok, I hear you say would I really have THAT many shapes in Excel worksheets. Well, I was surprised when I realised how many shapes I had generated creating a workflow diagram for a project I as was involved in. Yes, a lot. Some of them were not always visible either, hidden behind each other or stacked, formatted to be invisible, oh you name it I inherited an Excel piece of work like that. So, let’s write a quick bit of VBA code to get rid of all of the shapes from your Excel worksheet.

What Does The Macro Do?

The macro will delete ALL shapes in the active worksheet. This includes pictures, clipart, shapes, charts as well as smart art.

How Does The Macro Work?

Step 1. I want to make this macro available to any active worksheet and reuse if over it and over again so the first step in this process is to insert a new Module into my Personal Macro Workbook. If you want to read more about your Personal Macro Workbook then check out my blog posts below.

Macro Mondays -Creating and Updating Your Personal Macro Workbook

Macro Mondays – Create A Shortcut To Your Personal Excel Macro Workbook

Step 2. I need to declare a variable. Dim shp as Shape. This ensures Excel allocates memory for this value.

Step 3. We now use the For Next looping statement to instruct Excel to find each of the shapes in the active worksheet and it delete them. It will continue looping through the shapes until all are deleted.

Step 4. Once all shapes have been deleted the routines ends.

That is it. How simple is that? You do not need to go hunting on your worksheet to find all of the shapes. This small bit of code will do it all for you.

What Next? Want More Excel Tips?

If you want more Excel and VBA tips then sign up for my Monthly Newsletter where I share 3 Tips on the first Wednesday of the month and receive my free Ebook, 30 Excel Tips.

1

If you want to see all of the blog posts in the Macro Monday series. Click on the link below

How To Excel At Excel – Macro Mondays Blog Posts.

More Excel Tips_New1
Learn Excel With Our Excel Online Courses

Do You Need Help With An Excel Problem?.

I am pleased to announce I have teamed up with Excel Rescue, where you can get help with Excel FAST.

ExcelRescue.net

Delete all Shapes in Excel Workbook

In Excel a shape object can be:

A square box, round, call outs, star, arrow, line etc.,

Do you want to clear all these shapes from all worksheets? Then use this code.

Note: But just remember: Once the object is deleted & workbook is saved, the same shape cannot be recovered.

You only have to recreate these shapes dynamically again.

Sub Delete_All_Shapes_In_All_Sheets()
    'Declare Shape object & worksheet
    Dim shp As Shape, sh As Worksheet
    
    'Loop thru each worksheet
    For Each sh In ThisWorkbook.Sheets
    
        'Loop thru each shape in sheet
        For Each shp In sh.Shapes
        
            'Delete Shape object
            shp.Delete
        Next
    Next
    
End Sub

This code loops through each shape in the sheet & delete shapes, all of it, one by one, from the all worksheets.

If you have accidentally deleted any shape from the spreadsheet, then you will not be able to recover it again. You can only create a new one from Menu -> Insert -> Shapes or through dynamic shape creation.

What if we need to create only specific shape and not all?

Delete Shapes with Name

One idea to delete specific Shape is to use its name.

If not that, You can also choose other property of a shape like Title, Top, Width, height etc.,

Sub Delete_Shapes_with_Name(objNameToDelete As String)
    'Declare Shape object & worksheet
    Dim shp As Shape
    
    'Loop thru each shape in sheet
    For Each shp In ThisWorkbook.Sheets(1).Shapes
    
        'Verify that Shape has the name that needs to be deleted
        If shp.Name = objNameToDelete Then
            shp.Delete
        End If
        
    Next

End Sub

Inside code, check whether the property of any the shape matches with the value. If it matches then use .Delete on it.

Понравилась статья? Поделить с друзьями:
  • Excel vba удаление строк умной таблицы
  • Excel vba удаление символов в строке
  • Excel vba удаление пустая строка
  • Excel vba удаление листа без подтверждения
  • Excel vba удаление колонок