最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

excel - Auto Size Text To Fit Shape via vba - Stack Overflow

programmeradmin1浏览0评论

Please run the following code.

Sub Macro1()

'Delete all shapes
For i = ActiveSheet.Shapes.Count To 1 Step -1
    ActiveSheet.Shapes(i).Delete
Next i

'Add rectangle
With ActiveSheet.Shapes.AddShape(msoShapeRectangle, Left:=50, Width:=100, Top:=50, Height:=40)
    .TextFrame2.MarginLeft = 0
    .TextFrame2.MarginRight = 0
    .TextFrame2.MarginTop = 0
    .TextFrame2.MarginBottom = 0
    .TextFrame2.VerticalAnchor = msoAnchorMiddle
    .TextFrame2.TextRange.ParagraphFormat.Alignment = msoAlignCenter
    .TextFrame2.TextRange.Font.Size = 30
    .TextFrame2.AutoSize = msoAutoSizeTextToFitShape
    .TextFrame2.TextRange.Characters.Text = "Stackoverflow"
End With

End Sub

The following picture shows my question.

Thanks in advance

Please run the following code.

Sub Macro1()

'Delete all shapes
For i = ActiveSheet.Shapes.Count To 1 Step -1
    ActiveSheet.Shapes(i).Delete
Next i

'Add rectangle
With ActiveSheet.Shapes.AddShape(msoShapeRectangle, Left:=50, Width:=100, Top:=50, Height:=40)
    .TextFrame2.MarginLeft = 0
    .TextFrame2.MarginRight = 0
    .TextFrame2.MarginTop = 0
    .TextFrame2.MarginBottom = 0
    .TextFrame2.VerticalAnchor = msoAnchorMiddle
    .TextFrame2.TextRange.ParagraphFormat.Alignment = msoAlignCenter
    .TextFrame2.TextRange.Font.Size = 30
    .TextFrame2.AutoSize = msoAutoSizeTextToFitShape
    .TextFrame2.TextRange.Characters.Text = "Stackoverflow"
End With

End Sub

The following picture shows my question.

Thanks in advance

Share Improve this question asked 2 days ago Kram KramerKram Kramer 911 silver badge5 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

Can you try this?

Sub Test()
    Dim i As Long, myShp As Shape
    
    For i = ActiveSheet.Shapes.Count To 1 Step -1
        ActiveSheet.Shapes(i).Delete
    Next i
    
    Set myShp = ActiveSheet.Shapes.AddShape(msoShapeRectangle, Left:=50, Width:=100, Top:=50, Height:=40)
    
    With myShp
        .TextFrame2.MarginLeft = 0
        .TextFrame2.MarginRight = 0
        .TextFrame2.MarginTop = 0
        .TextFrame2.MarginBottom = 0
        .TextFrame2.VerticalAnchor = msoAnchorMiddle
        .TextFrame2.TextRange.ParagraphFormat.Alignment = msoAlignCenter
        .TextFrame2.TextRange.Font.Size = 1
        .TextFrame2.AutoSize = msoAutoSizeTextToFitShape
        .TextFrame2.TextRange.Characters.Text = "Stackoverflow"
        .TextFrame2.WordWrap = msoFalse
        
        Do While .TextFrame2.TextRange.BoundWidth < myShp.Width
          .TextFrame2.TextRange.Font.Size = .TextFrame2.TextRange.Font.Size + 1
        Loop
    End With
End Sub

Your macro code is include ".TextFrame2.TextRange.Font.Size = 30" already. You can change 30 to 17 or need font size.

发布评论

评论列表(0)

  1. 暂无评论