Search code examples
excelvbahyperlinkpowerpointpaste

Paste link to a textbox in Powerpoint from Excel


I am trying to paste text to a textbox in a PowerPoint slide then add a link to that text from the content of another cell in excel. I cannot seem to get the object definition correctly. I am starting from a macro enabled excel file and have a ppt file opened with one blank slide opened.
I keep getting this error:

Run-time error '-2147188160 (80048240)':
ActionSettings.Item: Integer out of range. 0 is not in Index's valid range of 1 to 2.

Here's the code I used from excel vba. I had a ppt blank file opened for this test.

Sub Add_Hyperlink_to_Text_in_Powerpoint()

'  to add the hyperlink to the actual text not the frame.

    Dim sh As Object
    Dim pp, ppApp, pptPres As Object
    Const leftcm As Single = 0, topcm As Single = 0 'just for test
    
   'define ppt application and file
    Set ppApp = CreateObject("PowerPoint.Application")
    Set pptPres = ppApp.ActivePresentation
   
   'create shape to paste text and link
    Set sh = pptPres.Slides(1).Shapes.AddShape(Type:=msoShapeRectangle, Left:=leftcm, Top:=topcm, Width:=260, Height:=35)
   
   'paste text in textbox
    sh.TextFrame.textRange.Text = "This is a Link"
    
    'paste link in text of textbox
    With sh.TextFrame.textRange.ActionSettings(ppMouseClick)
        .Action = ppActionHyperlink
        '.Hyperlink.Address = "https://www.google.com"
        .Hyperlink.SubAddress = "73. PowerPoint Presentation"
        .Hyperlink.TextToDisplay = sh.TextFrame.textRange.Text
    End With
    
End Sub

Solution

  • If the code is exectured in Excel/Word VBA, all PPT VBA consts should be replaced with its value.

        'paste link in text of textbox
        With sh.TextFrame.TextRange.ActionSettings(1)  ' ppMouseClick = 1 
            .Action = 7 ' pActionHyperlink = 7 
            .Hyperlink.Address = "https://www.google.com"
            .Hyperlink.SubAddress = "73. PowerPoint Presentation"
            .Hyperlink.TextToDisplay = sh.TextFrame.TextRange.Text
        End With