edge37
Board Regular
- Joined
- Sep 1, 2016
- Messages
- 73
- Office Version
- 2021
- Platform
- Windows
Hi! I'm trying this code to toggle hide/unhide columns in my worksheet:
But when I do so, the objects on top of those columns (tables, drawings or text boxes) gets resized. Is there a way to hide/show columns in a way I can keep objects on top of them in the same place and size? Pic I sent show before/after applying the code.
Thanks
VBA Code:
Sub ToggleColumnsAFtoAIWithoutAffectingObjects()
Dim ws As Worksheet
Dim targetColumns As Range
Dim obj As Shape
' Set the worksheet
Set ws = ThisWorkbook.Sheets("10A (1)")
' Set the target columns
Set targetColumns = ws.Columns("AF:AI")
' Check current visibility and toggle
If targetColumns.EntireColumn.Hidden Then
targetColumns.EntireColumn.Hidden = False ' Unhide columns
Else
targetColumns.EntireColumn.Hidden = True ' Hide columns
End If
' Loop through shapes (objects) and ensure they remain visible
For Each obj In ws.Shapes
' If the shape's top-left cell overlaps the target columns, make it visible
If Not Intersect(ws.Range(obj.TopLeftCell.Address), targetColumns) Is Nothing Then
obj.Visible = True
End If
Next obj
End Sub
Thanks