如何使用 VBA 在表格中添加句点?

How do I use VBA to add periods in tables?

我有以下代码可以在 PPT 幻灯片的正文中添加句点:

Sub TitlePeriod()

On Error Resume Next

Dim sld As Slide
Dim shp As Shape
Dim strTitle As String

For Each sld In ActivePresentation.Slides
    If sld.Shapes.HasTitle = True Then 'check if there is a title
        strTitle = sld.Shapes.Title.TextFrame.TextRange.Text
    Else
        strTitle = ""
    End If
    For Each shp In sld.Shapes
        'add periods only if text of shape is not equal to title text.
        If strTitle <> shp.TextFrame.TextRange.Text Then
             shp.TextFrame.TextRange.AddPeriods
        If shp.HasTable Then
            shp.TextFrame.TextRange.AddPeriods
        End If
    End If
    Next shp
Next sld

End Sub 

我正在尝试向代码中添加一些位,以便在幻灯片中向 tables 添加句点

If shp.HasTable Then shp.TextFrame.TextRange.AddPeriods

当我运行代码没有错误,但table中没有添加句点。想要一些关于如何解决这个问题的建议或提示。

提前致谢

首先,我想提供一些建议。当试图找出这样的问题时,最好尝试检查局部变量 window 中的对象。这样,您可以搜索对象的属性(在本例中为形状对象 shp,它恰好是 Table)并找出需要修改哪些属性才能获得所需的结果。没有冒犯的意思,但是从你的问题来看,你似乎是 VBA 的新手,并且在某处找到了一些这样的代码。

此外,代码实际上对我造成了错误,因为 Table 形状没有文本框(虽然我只做了一个测试 table...也许你的实际上有一)。我为 textFrame 添加了一个检查。

对于您的具体问题,具有 table 的形状对象具有 Table 属性 需要用于向单元格添加内容。反过来,Table 有一个 Columns 对象,它是列的集合。您需要遍历所有列。每列都是单元格的集合,因此您需要遍历单元格。每个单元格都有您要查找的 textframe 和 textrange 对象,因此您需要 运行 这些对象上的 .AddPeriods 方法。

 Sub TitlePeriod()

     On Error Resume Next

     Dim sld As Slide
     Dim shp As Shape
     Dim strTitle As String
     Dim myTable As Table
     Dim myColumns As Columns
     Dim col As Column
     Dim myCell As Cell


     For Each sld In ActivePresentation.Slides
          If sld.Shapes.HasTitle = True Then 'check if there is a title
                strTitle = sld.Shapes.Title.TextFrame.TextRange.Text
          Else
                strTitle = ""
          End If
          For Each shp In sld.Shapes
                'add periods only if text of shape is not equal to title text.
                 If shp.TextFrame.HasText Then 'check to make sure there is text in the shape
                      If strTitle <> shp.TextFrame.TextRange.Text Then
                            shp.TextFrame.TextRange.AddPeriods
                      End If
                 End If

                 If shp.HasTable Then 'Check to see if shape is a table
                      Set myTable = shp.Table 'Get the table object of the shape
                      Set myColumns = myTable.Columns 'Get the columns of the table
                      For Each col In myColumns 'Loop through the columns
                            For Each myCell In col.Cells 'Loop through the cells in the column
                                       myCell.Shape.TextFrame.TextRange.AddPeriods 'Add periods to the cell
                             Next myCell
                       Next col
                 End If
           Next shp
      Next sld

 End Sub