Search code examples
vbapowerpoint

Create a table and reference it


I am trying to read every two lines of text, create a slide, and insert each line in the cells of a 2 by 1 table respectively using VBA code.

Public Sub newSlide()
    Dim FileNum As Integer
    Dim DataLine As String
    Dim Count As Integer
    Count = 0
    FileNum = FreeFile()
    Open "C:\Users\ADMININST\Documents\my.txt" For Input As #FileNum
        
    While Not EOF(FileNum)
        Count = Count + 1
        Line Input #FileNum, DataLine ' read in data 1 line at a time
        ' decide what to do with dataline,
        ' depending on what processing you need to do for each case
        Debug.Print ("Love you")
        If Count Mod 2 = 1 Then
            Dim pptSlide As Slide
            Dim pptLayout As CustomLayout
     
            Set pptLayout = ActivePresentation.Slides(1).CustomLayout
            Set pptSlide = ActivePresentation.Slides.AddSlide(2, pptLayout)
            'ActivePresentation.Slides.Add Index:=ActivePresentation.Slides.Count + 1, Layout:=ppLayoutCustom
        
            Dim pptTable As Table
            pptTable = pptSlide.Shapes.AddTable(2, 1).Select
            pptTable.Cell(1, Count Mod 2) = DataLine
        End If
    Wend
End Sub

I get a compile error;

"expected Function or variable" for the line below. It seems Select is not returning the table.

pptTable = pptSlide.Shapes.AddTable(2, 1).Select

Solution

  • Here's a rework of your code:

    Dim pptTable As Shape
    Set pptTable = pptSlide.Shapes.AddTable(2, 1)
    pptTable.Table.Cell(1, Count Mod 2).Shape.TextFrame.TextRange.Text = DataLine
    

    The object produced by Shapes.AddTable is a Shape, which contains a table. So I changed the Dim statement to make that work.

    The Select is unneccessary. Using Set makes pptTable a shape that you can refer to.

    When your code gets past that error, it runs into another in the next line. You need to refer to the Text inside the TextRange, inside the TextFrame, inside the Shape, inside the cell to place the string.