Macro to loop through siblings

Greg shared this question 3 years ago

Hi, I was hoping that someone could please help me.

I want to loop through a topic with a string of sub topics. I want all the subtopics to be arranged as single sub topics. See below.

I am finding it hard to use the macro "topics collection" to get the desired response. Can someone provide me with some code options?

Supplementary question what are siblings in code language and how do they work? I found reference to first, last and next. Are these the same as sub topics?


Replies (2)


Hello Greg

To answer your second question first: "siblings" are the other topics at the same level in the subtopics of a parent topic. In your example map above, Blue is Aqua's next sibling, Purple is Red's previous sibling, Grey is the first sibling of all in that collection, and Yellow is the last sibling of all in that collection. Grey's previous sibling will be an empty pointer, so will Yellow's next sibling.

To move a string of subtopics up to the same parent requires the "Insert" method of a topic collection. This moves a topic from its current position to another collection. To be honest the coding for this is more complex than doing it by hand, but the following will do the transformation you require if you select the top level topic (e.g. Magenta) and run the macro. It continually promotes the first grandchild topic to be a child topic, until there are no more grandchildren.

Sub Main
	Dim m_Topic As Topic
	Dim m_Subtopic As Topic
	Dim b_Loop As Boolean

	Set m_Topic = ActiveDocument.Selection.PrimaryTopic

	b_Loop = True
	While b_Loop
		b_Loop = False
		For Each m_Subtopic In m_Topic.SubTopics ' for each child
			While m_Subtopic.SubTopics.Count > 0 ' while there is a grandchild
				m_Topic.SubTopics.Insert(m_Subtopic.SubTopics.Item(1)) ' promote it to child
				b_Loop = True ' leave outer loop when there are no more grandchildren

End Sub


Thank you, Nick. The code worked to perfection. I appreciate your time and effort. Regards Greg