Find all shapes in word

Select objects, shapes, pictures or text boxes, to change or move them. Sizing handles indicate that a shape or object has been selected.

Click or tap the object to select it. If that doesn’t select it, go to Home > Select and do one of the following:

  • To select all of the text in the document, choose Select All.

  • To select objects that are hidden, stacked, or behind text, choose Select Objects. To select an object, click or tap when your pointer becomes a selection arrow White pointer with 4-headed arrow as it moves over an object. To select multiple objects, press and hold Ctrl while you click or tap the objects that you want.

  • To select text with similar formatting, choose Select All Text with Similar Formatting.

  • To open the task pane where you can select, multi-select, show, hide, or change the order of objects, choose Selection Pane, and then select the options that you want.

Select options on Home menu

Tips for selecting shapes and objects

To do this

Do the following

Select multiple objects.

Press and hold Shift or Ctrl while you select the objects.

Select an object that is under other objects and cycle forward through the stack of objects.

Select the top object, and then press Tab.

Select an object that is under other objects and cycle backward through the stack of objects.

Select the top object, and then press Shift+Tab.

Select objects that are part of a group.

Select the group, and then do one of the following:

  • To select one object, click or tap the object.

  • To select multiple shapes in a group, press and hold Shift or Ctrl while you click or tap the shapes.

Cancel the selection of one object at a time.

Press and hold Shift or Ctrl while you click or tap each object.

See Also

Group or ungroup shapes, pictures, or other objects

Select objects, shapes, pictures or text boxes, to change or move them. Sizing handles indicate that a shape or object has been selected.

Using the Selection Pane

If you can’t select an object or there many objects to select, use the Selection pane.

  1. Select one of the objects you want to manage.

  2. Go to Shape Format or Picture Format> Arrange  Arrange button > Selection Pane.

    Selection Pane button

  3. The Selection Pane opens with all your objects listed, and you can do any of the following:

    • Drag an item up or down in the list to change the order.    If you have objects that cover each other, this will bring an object to the front, or put it behind another object.

    • Choose to show or hide objects from the Selection Pane.    To hide an object, select the eye icon in the Selection Pane indicating that the object is Showing The Show icon in the Selection Pane. The icon changes to a simple icon indicating that the object is Hidden Shows the icon indicating that an object is hidden from view. To show the object once again, select the Hidden icon Shows the icon indicating that an object is hidden, and the object reappears.

    • Group or ungroup objects listed in the Selection Pane.    If you select multiple objects by using Command + Click, you can then group them or ungroup them by selecting Format Shape or Format Picture > Arrange  Arrange button> Group Objects.

      Group objects button

Hi all

I am new to VBA and new to this forum («Hello Lawrence»)

I have a word document with shapes that I added via the Insert Shapes menu entry

Some of the shapes are lines, others are rectangles and some are callouts. I even have a picture or two. (Some are in the header area)

I wanted a script to run through the shapes and select them. I tried this:

Sub FindShapes()

Dim doc As Word.Document, rng As Word.Range
Dim shp As Word.Shape

Set doc = ActiveDocument
Set tot = doc.Shapes

a = tot.Count

For Each shp In doc.Shapes
shp.Select
Debug.Print shp.Type; shp.ID, shp.Name

Next

End Sub

But it does not find all the shapes. In same cases it may find only one shape.

What am I doing wrong?

Thank you

Lawrence

How can I select all shapes in a document with C#.

I’m currently changing the language settings of a word document.

I was able to change the language using select all, unfortunately not all were selected like header/footer, text box or any shapes on the document. I manage somehow to set the language in header/footer. But I can’t find a way to set the language for shapes.

I have tried to do a quick macro, but I don’t know what the index for each shapes in the document.

This is the macro:

ActiveDocument.Shapes("Text Box 4").Select
ActiveDocument.Shapes.Range(Array("Text Box 4", "Rectangle 7")).Select
ActiveDocument.Shapes.Range(Array("Text Box 4", "Rectangle 7", _
    "Text Box 10")).Select
ActiveDocument.Shapes.Range(Array("Text Box 4", "Rectangle 7", _
    "Text Box 10", "Rectangle 11")).Select
Selection.LanguageID = wdEnglishUK

And this is what I deed in C#, but its not working…

        wordApp.ActiveDocument.Shapes.SelectAll();
        wordApp.Selection.LanguageID = Word.WdLanguageID.wdEnglishUK;

If try using this:

wordApp.ActiveDocument.Shapes.Range(??).Select; //I don't know what should I put inside the range
wordApp.Selection.LanguageID = Word.WdLanguageID.wdEnglishUK;

I hope someone here can help me. Or if you have better solution to change the language, please let me know.Tnx

  • Remove From My Forums
  • Question

  • hi all,

    I want to select all shapes and text from one page in Microsoft Word,now i can do this executing a VBA script in macros,but from shapes it can’t select inline shapes,i have to make all shapes inline,and i don’t
    want to do this.

    what should i do to select all shapes and text in one page including shapes which aren’t inline?

    i really appreciate your help.

    Best Regards.


    Elmira Frhn

Answers

  • Assuming the selection is already on the page of interest:
    Selection.GoTo what:=wdGoToBookmark, Name:=»page»

    Alternatively, if you haven’t yet selected the page:
    Dim Rng As Range, i As Long
    i = CLng(InputBox(«Please input the page #»))
    Set Rng = ActiveDocument.GoTo(What:=wdGoToPage, Name:=i)
    Set Rng = Rng.GoTo(What:=wdGoToBookmark, Name:=»page»)
    Rng.Select

    Note: In each case the floating shapes don’t get highlighted. That’s of no consequence as their anchors get selected anyway.


    Cheers
    Paul Edstein
    [MS MVP — Word]

    • Marked as answer by

      Monday, November 4, 2013 1:27 AM

Microsoft Word provides features to select multiple objects in Microsoft Word document. This article explains how to select multiple objects or shapes in the MS Word Document.

Microsoft Office 2010

Step (1). Open Microsoft Word 2010 document.

Step (2). Select multiple objects by holding Ctrl key down and mouse click on objects. This way we can select multiple objects.

If your document have so many overlapped objects, it is bit difficult to select them using mouse. Instead of this, you can select the multiple objects from Selection Pane. Following steps explain how to select multiple objects using Selection Pane.

Step (1). Click on Home tab and select Select item under Editing section. It will display a sub-menu.

Step (2). In sub-menu select Selection Pane… menu item. It will display Selection and Visibility window/pane. It will display the shapes on the current page.

Step (3). You can select multiple objects/shapes by holding Ctrl key down and mouse click on objects/shapes in the Selection and Visibility pane/window.

Another way of selecting multiple objects is by dragging the mouse over the objects with in the mouse dragged area. This is simple and easy to use feature. This feature was available in earlier versions of MS Word 2010. At the time of writing this article this feature is not available in MS Word 2010. Strange!

Following steps achieve this by converting the MS Word 2010 document to Word 97 – 2003 document type.

Step (1). Open Microsoft Word 2010 document.

Step (2). Save As the document to Word 97-20013 document type. The document may loose some of the features supported in Word 2010 document format. Be careful while converting the document to old format.

Step (3). Click on Home tab. It will display Home tab items.

Step (4). Select Select item under Editing section. It will display a sub-menu.

Step (5). In sub-menu select Select Objects menu item. This is a check menu item. Means if you click on Select Objects menu item on first time; Microsoft Word will enable you to select multiple objects. If you click on second time on Select Objects menu item; it will disable you to select multiple objects.

Step (6). Now drag your mouse pointer (by pressing left mouse button) over the objects you want to select.

Step (7). The objects which are there in the mouse dragged area will be selected and you can do operations on multiple selected objects or shapes.

by Code Steps

  • Remove From My Forums
  • Question

  • In Word 2010  VBA I want to advance to the next shape in a document and select the shape. The Next method of the Browser object seems ideal as it finds the next shape whether it is floating
    or inline. The following code moves the cursor to the anchor point of the next shape but does not select the shape:

            Application.Browser.Target = wdBrowseGraphic

       
    Application.Browser.Next

    The only way that I can see to then select the shape is to extend the range by one character and select the first shape in the range:

           Set aRange = Selection.Range

              
    With aRange

                   
    .MoveEnd unit:=wdCharacter

                  
    If .ShapeRange.Count > 0 Then  .ShapeRange(1).Select

                  
    If .InlineShapes.Count > 0 Then  .InlineShapes(1).Select

          
    End With

    The problem with this approach is that there may be more than one shape anchored at the same point and it seems impossible to determine which of the shapes Browser has found.

     Is there a way to do this?

Answers

  • Hi Kroak888,

    As you might be aware, you have to work with Shapes and Inline Shapes separately. The following sample code will locate both inline and floating style shapes and select them one at a time for further processing.

    If you need more help, let us know what you are trying to accomplish with the various shapes after you have selected them.

    Sub FindShapes()
        Dim doc As Word.Document, rng As Word.Range
        Dim shp As Word.Shape, iShp As Word.InlineShape
        
        Set doc = ActiveDocument
        For Each shp In doc.Shapes
            shp.Select
            Debug.Print shp.Type
        Next
        For Each iShp In doc.InlineShapes
            iShp.Select
            Debug.Print iShp.Type
        Next
    End Sub
    


    Kind Regards, Rich … http://greatcirclelearning.com

    • Marked as answer by

      Sunday, October 6, 2013 2:44 PM

  • I have worked out a convoluted way to find the next shape even if that shape is in a cluster of shapes having the same anchor point.

    The following code will determine a shapes position in the cluster. It is then a matter of advancing to the next shape in the cluster or if at the last shape, moving to the next shape after the cluster.

    ' determine the number of shapes remaining in its cluster
    ' a shape must be currently selected  
    Set aRange  =  Selection.Range
    aRange.MoveEnd Unit:=wdCharacter
    m = aRange.ShapeRange.Count
    ' move forward and back to put the cursor at the first tag
    With Application
      .Browser.Target = wdBrowseGraphic
      .Browser.Next
      .Browser.Previous
    End With
    Set aRange  =  Selection.Range
    aRange.MoveEnd Unit:=wdCharacter
    n = aRange.ShapeRange.Count
    ClusterPosition = n – m + 1
    

    I was able to write a routine to advance from wherever the cursor is in the document to the next floating or inline shape. Including the ability to go forward or backwards, I ended up with 75 lines of code.

    Surely there is a simpler way.

    • Marked as answer by
      Fei XueMicrosoft employee
      Sunday, October 6, 2013 2:43 PM

Доброго времени суток всем читателям и подписчикам блога scriptcoding.ru. В этой статье мы рассмотрим работу с коллекцией Shapes, которая позволяет добавлять различные графические объекты в Word документ.

По сути, используя методы данной коллекции, мы можем делать вставку таких графических объектов в Word как авто-фигуры, выноски, рисунки, диаграммы, полотна и многое другое. Также стоит уточнить, что по ходу статьи, под словом «фигура» будут подразумеваться все графические Word объекты (полотно, WordArt, SmartArtи так далее). Я не привожу примеров программного кода, самим программированием мы займемся, когда будет изучать по отдельности работу с каждым графическим объектом Word, которые создаются с помощью коллекции Shapes.

Содержание

  1. Коллекция Shapes – графические объекты в Word
  2. Shapes – свойства, работа с графическими объектами Word
  3. Shapes — методы, создание графических объектов в Word

Коллекция Shapes – графические объекты в Word

Shapes – свойства, работа с графическими объектами Word

Count— Возвращает количество фигур в коллекции.

Shapes — методы, создание графических объектов в Word

работа с графическими Word объектами

Основной функционал коллекции заключается в ее методах, большинство из которых будут возвращать класс Shape, а тот в свою очередь, будет предоставлять нужные свойства для конкретной фигуры. Например, мы добавили новое полотно в документ, для обработки данного полотна используется свойство CanvasItems, которое хранит ссылку на CanvasShapes. При добавлении новой линии в документ, нам нужно обратиться к свойству Line, которое хранит ссылку на класс LineFormat, который отвечает за обработку линий. И так далее, это логично, так как у каждого графического объекта в Word, например, выноски и WordArt есть различные возможности.

AddCanvas(Left, Top, Width, Height, Anchor) — Добавляет новое полотно в документ.

Anchor – Содержит ссылку на класс Range, который представляет текст, к которому нужно привязать полотно.

AddSmartArt(Layout, Left, Top, Width, Height, Anchor) – Вставка таких графических объектов Word в активный документ, как рисунок SmartArt. Начиная с версии Word 2010.

Layout – Ссылка на класс SmartArtLayout.

AddCallout(Type, Left, Top, Width, Height) – Добавляет текстовую выноску с линиями.

Type – Данный параметр определяет тип линии. Значения константы MsoCalloutType:

  • msoCalloutOne — 1 – Горизонтальная линия слева.
  • msoCalloutTwo — 2 – Горизонтальна линия с наклоном лева.
  • msoCalloutThree — 3 – Линия состоит из двух отрезков слева (один отрезок с наклоном, а другой горизонтальный).
  • msoCalloutFour — 4 — Линия состоит из трех отрезков справа (один отрезок с наклоном, другой горизонтальный и третий вертикальный).

AddLine(BeginX, BeginY, EndX, EndY) – Рисует линию с указанными начальными и конечными координатами.

AddConnector(Type, Left, Top, Width, Height) – Рисует соединительную линию.

Type – Тип линии, значение константы MsoConnectorType:

  • msoConnectorStraight — 1 — Прямая линия.
  • msoConnectorElbow — 2 – Прямое колено.
  • msoConnectorCurve — 3 – Изогнутое колено.
  • msoConnectorTypeMixed — -2 – Смешанные значения.

AddShape(Type, Left, Top, Width, Height) – Вставка графических объектов в Word, которые представляют указанную автофигуру.

Type – Определяет тип фигуры, значение константы MsoAutoShapeType.

AddPicture(FileName, LinkToFile, SaveWithDocument, Left, Top, Width, Height) — Добавляет изображения. Возвращает класс Shape, представляющий картинку и добавляет ее в коллекцию CanvasShapes. Обязательный только первый параметр.

FileName – Путь к файлу и его имя.

LinkToFile – True – привязать изображение к файлу, из которого он был создан. False – сделать изображение независимым от файла, по умолчанию.

SaveWithDocument – True — сохранить связанный рисунок с документом. Значение по умолчанию False. Если использовать значение False, то может возникнуть ошибка. Работа с графическими Word объектами.

создание в word графических объектов

AddLabel(Orientation, Left, Top, Width, Height) — Добавляет текстовую область.

Orientation – Задает ориентацию текста. Значение константы MsoTextOrientation:

  • msoTextOrientationHorizontal — 1 — Горизонтальная.
  • msoTextOrientationUpward — 2 – Направление вверх.
  • msoTextOrientationDownward — 3 – Направление вниз.
  • msoTextOrientationVerticalFarEast — 4 – Вертикальное направление для азиатских языков.
  • msoTextOrientationVertical — 5 – Направление вниз.
  • msoTextOrientationHorizontalRotatedFarEast — 6 — Горизонтальное направление для азиатских языков.

AddTextbox(Orientation, Left, Top, Width, Height) — Добавляет текстовое поле.

AddTextEffect(PresetTextEffect, Text, FontName, FontSize, FontBold, FontItalic, Left, Top) – Создание графического объекта WordArt в Word.

PresetTextEffect – Определяет эффект текста WordArt. Значение константы MsoPresetTextEffect.

Text — Текст в WordArt.

FontName — Название шрифта, используемого в WordArt.

FontSize — Размер шрифта в пунктах.

FontBold – Содержит логическое значение, определяющее, нужно ли сделать шрифт жирным (true) или нет (false).

FontItalic — Содержит логическое значение, определяющее, сделать шрифт курсивом (true) или нет (false).

Item(index) — Возвращает отдельный класс Shape в коллекции Shapes по его индексу.

Range(index) — Возвращает ShapeRange, представляющий графические объекты в Word внутри заданного диапазона. Данный метод позволяет выбрать несколько графических Word объектов для будущей их группировки или обработки.

Index — Указывает, какие графические объекты Word должны быть включены в указанный диапазон. Может быть целое число, указывающее порядковый номер фигуры в коллекции Shapes, строка, которая определяет имя фигуры, или массив, содержащий целые числа или строки. Например:

ActiveDocument.Shapes.Range(Array("Oval 5", "Rectangle 4")).Select

SelectAll() — Выбирает все графические объекты в Word в коллекции Shapes. Этот метод не выбирает классы InlineShape. Вы не можете использовать этот метод, чтобы выбрать более одного полотна.

AddPolyline(SafeArrayOfPoints) — Добавляет открытый или закрытый полигон. Возвращает Shape, который представляет многоугольник и добавляет его в коллекцию CanvasShapes.

SafeArrayOfPoints — Массив с парами координат, которые определяют вершины и контрольные точки кривой.

AddCurve(SafeArrayOfPoints) — Возвращает Shape, который представляет кривую Безье.

BuildFreeform(EditingType, X1, Y1) – Создание свободного графического объекта в Word, вернет класс FreeformBuilder. По сути, данный метод позволяет добавить только первый узел будущей фигуры, а уже далее нужно использовать функционал класса FreeformBuilder.

EditingType – Свойства узла. Значение константы MsoEditingType:

  • msoEditingAuto — 0 – Подключение узла.
  • msoEditingCorner — 1 — Угловой узел.
  • msoEditingSmooth — 2 — Гладкий узел.
  • msoEditingSymmetric — 3 — Симметричный узел.

X1 и Y1— Определяют положение узла в пунктах.

AddChart(Style, Type, Left, Top, Width, Height, Anchor, NewLayout) — Добавляет диаграмму в документе.

Style — Стиль диаграммы, целое значение

Type — Тип диаграммы, значение константы XlChartType.

Left – Положение диаграммы в пунктах от левого края.

Top — Положение диаграммы в пунктах от верхнего края.

Width и Height — Ширина и высота в пунктах.

Anchor – Диапазон, который будет связан с графическим объектом в Word.

NewLayout — Если значение true, то график будут вставлен с помощью новых динамические правил форматирования.

AddOLEControl(ClassType, Range) – Добавляет в документ элемент управления ActiveX (ранее известный как элемент управления OLE). Возвращает InlineShape, представляющий новый элемент управления ActiveX. Чтобы изменить свойства элемента управления ActiveX, можно использовать свойство Objectкласса OLEFormat для заданной фигуры.

ClassType — Данный параметр принимает строковое значение, которое содержит имя элемента управления ActiveX. Например:

  • CheckBox — «Forms.CheckBox.1».
  • ComboBox — «Forms.ComboBox.1».
  • CommandButton — «Forms.CommandButton.1».
  • Frame — «Forms.Frame.1».
  • Image — «Forms.Image.1».
  • Label — «Forms.Label.1».
  • ListBox — «Forms.ListBox.1».
  • MultiPage — «Forms.MultiPage.1».
  • OptionButton — «Forms.OptionButton.1».
  • ScrollBar — «Forms.ScrollBar.1».
  • SpinButton — «Forms.SpinButton.1».
  • TabStrip — «Forms.TabStrip.1».
  • TextBox — «Forms.TextBox.1».
  • ToggleButton — «Forms.ToggleButton.1».

Range — Диапазон, в котором нужно разместить элемент управления ActiveX. Если этот аргумент опущен, то ActiveX размещается автоматически.

  • Home
  • Forum
  • VBA Code & Other Help
  • Word Help
  • [SOLVED] Finding Shapes in a document

  1. 09-10-2012, 05:13 PM


    #1

    Finding Shapes in a document

    I want to find the next shape or textbox in a document following on from the current selection. I want the order in the document not the order in the Shapes collection. I am using the code:

    If Selection.ShapeRange.Count > 0 Then ' selection is inside a shape
       Selection.ShapeRange(1).Anchor.Paragraphs(1).Range.Select
       Selection.MoveDown unit:=wdLine ' move down one line from anchor
      End If
      Set pRange = Selection.Range
      pRange.End = ActiveDocument.Content.End
      If pRange.ShapeRange.Count >0 Then
       For Each sHp In pRange.ShapeRange
          Exit For
      Next sHp
      End if

    The problem with this code is that if there are several shapes anchored to the same paragraph mark then only the first of these is selected and the others are passed over.

    Can anyone solve my problem?

    Last edited by Aussiebear; 04-02-2023 at 04:50 PM.

    Reason: Adjusted the code tags


  2. 09-11-2012, 08:37 AM


    #2

    Why not just nest your shapes loop in a for each paragraph loop.

    Note, this may be a slow way to do what you’re doing, but since you haven’t provided any specifics, here is a generic answer. This will only go through the main body of the document (no shapes in headers, footers, etc).

    Sub Demo()
        Dim oPara As Paragraph
        Dim oShp As Shape
    For Each oPara In ActiveDocument
       For Each oShp In oPara.Range.ShapeRange
          'do whatever you want here
          Debug.Print oShp.Name
       Next
        Next
    End Sub

    Last edited by Aussiebear; 04-02-2023 at 04:51 PM.

    Reason: Adjusted the code tags

    _______________________________________________
    Please don’t cross-post without providing links to your cross-posts. We answer questions for free. Please don’t waste the time of the people helping you.
    For cross-posting etiquette, please read: http://www.excelguru.ca/content.php?184

    — Frosty


  3. 09-12-2012, 01:39 PM


    #3

    My requirement is to go to the next shape from a current cursor position or from a current shape selection. The issue is that the current shape may be anchored from a paragraph character that also anchors other shapes so it is not simply a matter of advancing to the next paragraph.

    The solution that I currently have is if the current selection is a shape, check its anchor character for multiple shapes, find the current shape’s name and advance by one shape. If the current shape is the last in the group then advance to the next paragraph. The resultant code is:

     
     If Selection.ShapeRange.Count > 0 Then ' selection is inside a shape
       shName = Selection.ShapeRange(1).Name ' store name of current shape
       Set aRange = Selection.ShapeRange(1).Anchor.Paragraphs(1).Range
       k = aRange.ShapeRange.Count
       i = 1
       Do While shName <> aRange.ShapeRange(i).Name And i < k
       i = i + 1
       Loop
       i = i + 1
       ' if i>k then current shape is last in anchored group
       If i <= k Then
          Set sHp = aRange.ShapeRange(i)
          GoTo markShape
       End If
       Selection.MoveDown unit:=wdLine ' move down one line from anchor
      End if
      ' ---
        Set pRange = Selection.Range
      pRange.End = ActiveDocument.Content.End
      If pRange.ShapeRange.Count < 1 Then
       MsgBox "No shapes after current selection"
       Exit Sub
      End If
      For Each sHp In pRange.ShapeRange
       Exit For
      Next sHp
    markShape:
      ' sHp is the desired shape

    This works in most cases but it is possible to have more than one shape with the same name which could cause an endless loop if they have the same anchor. Also, the shapes are not necessarily in order in the document.

    Last edited by Aussiebear; 04-02-2023 at 04:53 PM.

    Reason: Adjusted the code tags


  4. 09-12-2012, 02:01 PM


    #4

    When you say shapes are not necessarily «in order» — what do you mean? That the placement of the shape on the page may not be indicative of the order of the shapes in the .Shapes collection of whatever paragraph you’re currently in?

    I don’t think that issue will be particularly solvable, unless you can give more criteria on what you would define as the «next» shape (lower? more to the right? both?).

    It’s hard to provide a compete solution when you only provide snippets of code. While providing snippets of code is nice, in that you are limiting how much you want us to read while trying to provide you a solution, it also limits the solutions.

    Does the above code work? If so, great. If not, can you give better criteria by what you mean by «next» shape when there are multiple shapes anchored to a given paragraph?

    Why do you need the functionality in code of going to the «next» shape— what are you then doing? I assume a function which cycles through all shapes in the document, selecting each one in turn, is not desirable. So you’re trying to do some kind of CTRL+DOWN functionality for shapes only (the way that works by jumping the cursor to the next paragraph) — why?

    Is using a mouse not good enough, when there are multiple shapes anchored to a single paragraph? Shapes are, by definition, a (typically) floating graphical object, not defined by linear anchor position in the document. In general, the standard way to interact with such shapes is to use the mouse.

    What do you want to happen when there are groups of shapes? Select the group, then individual elements?

    There is a potential can of worms thing going here… we might be able to help avoid that if you can give more of a «why» to this question.


  5. 09-12-2012, 05:18 PM


    #5

    When editing a document, it is desirable to step through the shapes in a document and perhaps edit text if the shape is a text box or adjust its position on the page or chase up a link if it is linked to another source. As Word has 24 types of shapes, it is useful to display and alter a shape’s characteristics without needing to click through Word’s wretched menus.

    I use a non-modal form containing buttons to advance to the next shape, display the shape’s parameters and carry out other functions such as changing the anchoring and the word wrap. The form is displayed all the time making it possible to select a shape and either manually change or use the change buttons on the form. Then, the next shape can be selected by clicking the Next Shape button. It is important to carry out the changes in order in the document because of the cascading changes to layout that can occur.

    It is sometimes not immediately obvious if text on a page is in-line or is in a borderless textbox or table and the shapes search routine helps quickly identify these things. (I also have a find next table routine).

    All of this is intended to make an editor’s life easier and more productive. When editing a 600 page document with 200 tables, 150 text boxes and numerous pictures and other shapes, any little help is worthwhile.

    My post was intended to get suggestions for overcoming a knotty problem that I had. I only posted the relevant snippet of a much larger routine.

    My web site showing the macros that I am developing is:
    http://www.editordie.com.au/editorkae/index.html


  6. 09-13-2012, 09:22 AM


    #6

    Okay… but you didn’t really answer the most pertinent question: how would you define the proper «order» of shapes anchored to the same paragraph?

    I think some of your navigation tools will start to become obsolete with later versions of Word (the Selection pane shows all shapes, and their names, on the current page).

    In addition, have you looked at the Application.Browser object? That is a quick way of navigating various elements of the document. It seems to me that you should be able to use that to navigate both graphics and tables, and then layer your own For each shape in selection.paragraph(1).shapes loop within that.

    Application.Browser.Targer = wdBrowseGraphic
    Application.Browser.Next (and .Previous, etc)

    Not sure where to go from here… I totally understand consolidating disparate Word functionality for the purposes of a particular workflow. But I would suggest, where possible, using whatever native functionality exists, rather than trying to re-write your own version of that native functionality.

    If there’s anything else to do here, please let us know.


  7. 09-13-2012, 02:34 PM


    #7

    Thanks for your comments.


  8. 09-13-2012, 02:41 PM


    #8

    Sure thing.

    I noticed you said you have code which manipulates the anchor of a shape. Everytime I have tried to do that, is been kludgy. Are you doing something other than cutting and pasting the shape at a new range? Do you check whether the shapes positional info is relational or absolute?

    Better ways of navigating elements of a document are very useful functions. Just wondering if you’re reinventing the wheel on some of this, rather than simply displaying a more organized method for using built in functionality.

    _______________________________________________
    Please don’t cross-post without providing links to your cross-posts. We answer questions for free. Please don’t waste the time of the people helping you.
    For cross-posting etiquette, please read: http://www.excelguru.ca/content.php?184

    — Frosty


  9. 09-13-2012, 11:49 PM


    #9

    I agree that I am to some extent re-inventing the wheel. I started in the days of Word97 and by the time Word2007 came along improvements to Word had made some of my stuff obsolete and I ditched much of it. The remainder is specific to editing and is very useful for those users.

    These are some of Word’s foibles in relation to shapes that I have uncovered. I am sure that there are many more.

    In Word 2010, shapes can be dragged up and down and the anchor point will move with the shape provided the anchor is not locked. It is also possible to drag onto a different page. Earlier Word versions had problems doing these things.

    If you select the anchor paragraph, all shapes anchored to that paragraph are highlighted. If a shape has been dragged vertically then a “phantom” shape is also highlighted. The anchor point is at the start of the paragraph but you must select the whole paragraph in order to highlight the attached shapes.

    There doesn’t seem to be a way of changing the anchor point in VBA. The anchor property is read only.

    Shapes can be moved relative to the anchor by using the IncrementTop and IncrementLeft methods or by setting relative positions in the Layout menu.

    There are two shape collections – Shapes and InlineShapes, as well as a Tables collection. If a shape object is converted between InlineShape and Shape it gets a split personality and is a member of both collections. This can introduce a problem with some of the methods that are present in one and not the other object.

    Here is some code that shows a difference in result between Selection and Range objects. The First count is 0 and the Second count is 1 despite them referring to the same range.

    Sub showAnchor()
      ' run with cursor in a shape or textbox
      Dim aRange As Range
         Selection.ShapeRange(1).Anchor.Paragraphs(1).Range.Select
         MsgBox "First count=" & Selection.ShapeRange.Count
         Set aRange = Selection.Range
         MsgBox "Second count=" & aRange.ShapeRange.Count
      End Sub

    Last edited by Aussiebear; 04-02-2023 at 04:53 PM.

    Reason: Adjusted the code tags


  10. 09-14-2012, 02:16 AM


    #10

    To see what’s involved in working with shapes via their location on the page, see:
    http://www.msofficeforums.com/word-v…html#post39302
    Although the code there is specifically for working with frames, working with other kinds of shapes is essentially the same.

    Cheers
    Paul Edstein
    [Fmr MS MVP — Word]


  11. 09-14-2012, 02:20 AM


    #11

    Quote Originally Posted by smallken

    There doesn�t seem to be a way of changing the anchor point in VBA. The anchor property is read only.

    You do that by working with the anchor’s range — you can cut & paste it to wherever you want.

    If a shape object is converted between InlineShape and Shape it gets a split personality and is a member of both collections.

    Umm, no, they’re strictly one or the other.

    Cheers
    Paul Edstein
    [Fmr MS MVP — Word]


  12. 09-18-2012, 01:18 AM


    #12

    Sure thing. I noticed you said you have code which manipulates the anchor of a shape.


  13. 09-18-2012, 03:30 AM


    #13

    Here’s a fairly basic example. It relocates the first shape in the document to the first page. Test it with a shape on, say, the 2nd page.

    Sub Test()
    Dim Rng As Range
    With ActiveDocument
       Set Rng = .GoTo(What:=wdGoToPage, Name:="1")
       .Shapes(1).Anchor.Cut
       Rng.Paste
    End With
    End Sub

    Note that, in real life, you’d probably want to get the shape’s top & left settings so you can reposition it correctly at the new location.

    Last edited by Aussiebear; 04-02-2023 at 04:54 PM.

    Reason: Adjusted the code tags

    Cheers
    Paul Edstein
    [Fmr MS MVP — Word]


  14. 09-24-2013, 03:03 AM


    #14

    Finding Shapes in a document

    After two years, I finally got around to revisiting the problem and managed to devise a solution. The objective is to advance to and select the next (or previous) shape in the document whether the shape is floating or inline.

    I followed up on Frosty’s suggestion of using Application.Browser.Next. The result is the cursor at the anchor point of the next shape but the shape itself is not selected. In trying to determine which shape Browser has found, problems arise if more than one shapes is anchored to the same point.

    Below is my solution. It is complex but it works. I am wondering if there is a simpler solution.

    Sub getFollowingShape()
      GetNextShape (True)
    End Sub
    
    Sub getPreviousShape()
      GetNextShape (False)
    End Sub
    
    Function anchorsN() As Long ' number of shapes hanging off anchor
    Dim anRange As Range
      Set anRange = Selection.Range
      anRange.MoveEnd unit:=wdCharacter
      anchorsN = anRange.ShapeRange.Count
    End Function
    
    Sub GetNextShape(isNext As Boolean)
    Dim aRange As Range
    Dim shp As Shape
    Dim j As Long
    Dim mS As Long
    Dim mI As Long
    Dim kS As Long
    Dim k As Long
    Dim kA As Long
    Dim kB As Long
      Application.Browser.Target = wdBrowseGraphic
      With Selection
        mS = .Range.ShapeRange.Count
        mI = .InlineShapes.Count
        kS = .Range.Characters.Count ' =1 if only shape is selected
        ' ***************************
        ' if there are no shapes or there are more than one shape in selection
        '   then search from collapsed selection
        If (mS = 0 And mI = 0) Or kS > 1 Or mS > 1 Or mI > 1 Then
          kA = 1
          kB = 1
          If isNext Then
            .Collapse direction:=wdCollapseStart
          Else
            .Collapse direction:=wdCollapseEnd
          End If
        Else  '  selection is a single shape only with single character range
          If mI < 1 Then
            kA = anchorsN ' anchors from current shape
            If isNext Then
              Application.Browser.Next ' dance to pick up all anchors
              Application.Browser.Previous
            Else
              Application.Browser.Previous ' fixes problem if first or last shape
              Application.Browser.Next
            End If
            kB = anchorsN ' total number of shapes at anchor
            kA = kB - kA + 1 ' position of current shape in anchor list
          End If
        End If
      End With
     ' ***************************
        If isNext Then
          Application.Browser.Next
        Else
          Application.Browser.Previous
        End If
     ' ***************************
     ' **** determine k = shape item no ******
        If kB = 1 Then
          If isNext Then
            k = 1
          Else
            k = anchorsN
          End If
        Else ' multi shapes at anchor
          If isNext Then
            k = kA + 1
            If k > kB Then k = 1
          Else
            k = kA - 1
            If k < 1 Then k = 1
          End If
        End If
        Set aRange = Selection.Range
        With aRange
          .MoveEnd unit:=wdCharacter
          If .ShapeRange.Count > 0 Then
            .ShapeRange(k).Select
          Else
            If .InlineShapes.Count > 0 Then .InlineShapes(1).Select
          End If
        End With
    End Sub


  15. 09-24-2013, 05:10 PM


    #15

    The remainder is specific to editing and is very useful for those users.

    Shapes have been around since the dawn of Drawing Objects and have never really supposed to have been used as Controls, but it was the easiest quickest solution MS could come up with when Form type controls, (Forms Toolbar,) were needed.

    How hard would it be to convert to all MsForms Controls, (Controls Toolbar?) They are a lot easier to program with IMO.

    BTW, Thank you for returning with a solution to the problem. I’m going to mark it solved, but don’t let that keep you or anybody else from continuing to improve your solution.

    If you do decide to convert to MSForms controls, lets start another thread about them.

    I expect the student to do their homework and find all the errrors I leeve in.



Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules

We’re sorry Aspose doesn’t work properply without JavaScript enabled.

Понравилась статья? Поделить с друзьями:
  • Find crop in word
  • Find all italics in word
  • Find excel по русски
  • Find column of data in excel
  • Find all instances of a word in word