Adding a loop without Excel crashing

dcoker

New Member
Joined
Dec 13, 2018
Messages
36
Can anyone help with adding a loop here so that no text boxes overlap? I have tried to add a loop but Excel stops responding and I have to force close Excel.



VBA Code:
Sub MoveOverlappingTextBoxes()
    Dim ws As Worksheet
    Dim tb As Shape
    Dim i As Integer
    Dim j As Integer
    Dim tb2 As Shape

    Set ws = ActiveSheet

    For i = 1 To ws.Shapes.Count
        Set tb = ws.Shapes(i)
        If tb.Type = msoTextBox Then
            For j = i + 1 To ws.Shapes.Count
                Set tb2 = ws.Shapes(j)
                If tb2.Type = msoTextBox Then
                    If tb2.Type = msoTextBox And tb.Name <> tb2.Name Then
                    If Not (tb.Top > tb2.Top + tb2.Height Or _
                    tb.Left > tb2.Left + tb2.width Or _
                    tb.Top + tb.Height < tb2.Top Or _
                    tb.Left + tb.width < tb2.Left) Then
                        tb.Top = tb.Top + tb2.Height + 5
                        tb.Left = tb.Left + tb2.width + 5
                        tb2.Top = tb2.Top - tb.Height - 5
                        tb2.Left = tb2.Left - tb.width - 5
                    End If
                    End If
                End If
            Next j
        End If
    Next i
 
    
End Sub
 

Excel Facts

How to find 2nd largest value in a column?
MAX finds the largest value. =LARGE(A:A,2) will find the second largest. =SMALL(A:A,3) will find the third smallest

Forum statistics

Threads
1,214,561
Messages
6,120,245
Members
448,952
Latest member
kjurney

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top