Excel自动调整文本以适合形状

时间:2017-11-15 07:28:43

标签: excel vba excel-vba

我想将一些VBA添加到多图表模板中以自动调整标题文本以适合文本框。现在运行,但没有对文本框进行任何更改......

Sub TextBox()

Dim ws As Worksheet
Dim shp As Shape

' loop through sheets in this workbook
 For Each ws In ThisWorkbook.Worksheets
 ' loop through Chartobjects in sheet
   For Each shp In ws.Shapes

    If shp.Type = msoTextBox Then
        With shp.TextFrame2
            strTxt = .TextRange
            .DeleteText
            .WarpFormat = msoWarpFormat1
            .WordWrap = True
            .AutoSize = msoAutoSizeTextToFitShape
            .TextRange = strTxt
        End With
    End If
   Next shp
  Next ws

End Sub

1 个答案:

答案 0 :(得分:0)

您正在遍历工作表中的所有文本框,但如果您的文本框位于chartobject上,则需要稍微处理它。

Sub TextBox()

    Dim w As Worksheet
    Dim c As ChartObject
    Dim s As Shape

    For Each w In ActiveWorkbook.Worksheets
        For Each c In w.ChartObjects
            For Each s In c.Chart.Shapes
                If s.Type = msoTextBox Then
                    With s.TextFrame2
                        strTxt = .TextRange
                        .DeleteText
                        .WarpFormat = msoWarpFormat1
                        .WordWrap = True
                        .AutoSize = msoAutoSizeTextToFitShape
                        .TextRange = strTxt
                        .TextRange.Font.Name = "Calibri"
                        .TextRange.Font.Size = "8"
                    End With
                End If
            Next s
        Next c
    Next w

End Sub