Search code examples
excelvbatextbox

how to add text box/shape around each cell in the selection?


Is there a VBA code to add textboxes around each cell in the selection. textboxes should be exactly the size of the cell(similar to borders)?


Solution

  • You can use the .AddTextbox method. Loop through the cells in your selection, and use the cell's dimensional properties to set the dimensions of your textbox.

    Sub cellsToTextbox()
    
        Dim cel As Range
    
        For Each cel In Selection
            cel.Worksheet.Shapes.AddTextbox 1, cel.Left, cel.Top, cel.Width, cel.Height
        Next cel
    
    End Sub
    

    Modifying Textbox Properties

    If you wanted to change any of the textbox properties, I would do it while you are creating the textbox itself. My preferred method would be to wrap the entire .AddTextbox() method into a With statement, and change the individual properties there.

    Here's an example changing the VerticalAnchor property (I also moved your request to change the column size here from your comment to this example):

    Sub cellsToTextbox()
    
        Dim cel As Range
    
        For Each cel In Selection
            With cel.Worksheet.Shapes.AddTextbox(1, cel.Left, cel.Top, _
                            cel.Resize(ColumnSize:=3).Width, cel.Height)
    
                .TextFrame2.VerticalAnchor = msoAnchorMiddle
    
            End With
        Next cel
    
    End Sub