Проблемы с текстовыми полями, индивидуально гиперссылки на слайды с соответствующими названиями - PullRequest
0 голосов
/ 10 декабря 2018

Я собрал модуль электронного обучения.Я все еще очень новичок в VBA, хотя.Я пытаюсь сделать динамическое главное меню, которое содержит несколько текстовых полей.Если текст в текстовом поле соответствует заголовку слайда, тогда эта форма должна быть связана с соответствующим слайдом.В идеале, текстовые поля в главном меню должны содержать имена разделов и гиперссылки на первый слайд в названном разделе, но я не мог этого понять, поэтому вместо этого я сделал заголовок первого слайда в каждом разделе соответствующимтекст.Я искал и искал и подобрался как можно ближе.Я надеюсь, что кто-то может помочь мне закончить это.Я получил несколько ошибок, и у меня есть гиперссылка на текст, однако все ссылки приводят пользователя к последнему слайду в презентации вместо правильного слайда.Заранее благодарю за любые рекомендации !!

Вот код:

Sub TestMe()

'Original Source: http://www.steverindsberg.com/pptlive/FAQ00056.htm

Dim aSl As Slide 'active slide
Dim dSl As Slide 'destination slide
Dim Slde As Slide
Dim oSh As Shape
Dim aSl_ID As Integer
Dim aSl_Index As Integer
Dim dSl_ID As Integer
Dim dSl_Index As Integer
Dim sTextToFind As String
Dim hypstart As String
Dim Titl As String

Set aSl = Application.ActiveWindow.View.Slide 'active slide
aSl_Index = Application.ActiveWindow.View.Slide.SlideIndex 'active slide index
' Set ActiveSld_Index =
' Set DestinationSld_ID = oSl.SlideID
' Set DestinationSld_Index = oSl.SlideIndex


        For Each oSh In aSl.Shapes

            'If IsSafeToTouchText(oSh) = True Then

                sTextToFind = oSh.TextFrame.TextRange.Text

                'loop through slides looking for a title that matches the text box value

                On Error Resume Next
                Set dSl = FindSlideByTitle(sTextToFind)

                ' get the information required for the hyperlink
                dSl_ID = CStr(dSl.SlideID)
                dSl_Index = CStr(dSl.SlideIndex)

                ' find the text string in the body
                hypstart = InStr(1, sTextToFind, sTextToFind, 1)

                'make the text a hyperlink
                With oSh.TextFrame.TextRange.Characters(hypstart, Len(sTextToFind)).ActionSettings(ppMouseClick).Hyperlink
                .SubAddress = dSl_ID & "," & dSl_Index & "," & sTextToFind

                End With

            'End If

        Next oSh

End Sub

Public Function FindSlideByTitle(sTextToFind As String) As Slide

'Source: http://www.steverindsberg.com/pptlive/FAQ00056.htm

Dim oSl As Slide
Dim oSh As Shape

With ActivePresentation

    For Each oSl In .Slides

        For Each oSh In oSl.Shapes

            With oSh

                'If .HasTextFrame Then

                    'If Not .TextFrame.TextRange.Text Is Nothing Then

                    'myPres.Slides(1).Shapes.Title.TextFrame.TextRange

                    On Error Resume Next

                    If UCase(.TextFrame.TextRange.Text) = UCase(sTextToFind) Then

                        'If UCase(.TextRange.Text) = UCase(sTextToFind) Then

                            Set FindSlideByTitle = oSl


                        'End If

                    End If

                'End If

            End With

        Next

    Next

End With

End Function

Public Function IsSafeToTouchText(pShape As Shape) As Boolean

'Source: http://www.steverindsberg.com/pptlive/FAQ00056.htm

On Error GoTo ErrorHandler
If pShape.HasTextFrame Then
    If pShape.TextFrame.HasText Then
        ' Errors here if it's a bogus shape:
        If Len(pShape.TextFrame.TextRange.Text) > 0 Then
            ' it's safe to touch it
            IsSafeToTouchText = True
            Exit Function
        End If ' Length > 0
    End If ' HasText
End If ' HasTextFrame
Normal_Exit:
IsSafeToTouchText = False
Exit Function
ErrorHandler:
IsSafeToTouchText = False
Exit Function
End Function

Вот пересмотренный код.Я ходил кругами и теперь застрял.Любые предложения очень ценятся!

После того, как я восстановил исходную функцию (FindSlideByTitle), я продолжал получать сообщение об ошибке на .textframe.textrange, заставляя меня думать, что тип формы, который я использовал на моем слайде(freeform) нужен TextFrame2, поэтому я отредактировал это, что исправило ошибку, но с тех пор я не смог заставить гиперссылку работать и вместо этого пытался использовать GoTo Slide, включая родителя.

IЯ даже пытался создать массив всех произвольных форм на слайде, но я все еще новичок в этом, и, возможно, я еще не до конца понимаю концепции.В настоящий момент я не получаю никаких ошибок, однако, когда я нажимаю одну из фигур, внешний вид фигуры изменяется от щелчка, но никуда не уходит.

Я также включилизображение фактического слайда.

Slide

Sub TestLinkShapesToSlideTitles()


    Dim aSl, dSl, oSl As Slide 'active slide, destination slide
    Dim oSh As PowerPoint.Shape
    Dim aSl_ID, dSl_ID As Integer
    Dim aSl_Index, dSl_Index As Long
    Dim dSl_Title, hypstart, Titl As String
    Dim sTextToFind As String
    Dim numshapes, numFreeformShapes As Long
    Dim FreeformShpArray As Variant
    Dim ShpRange As Object
    Dim oPres As Presentation


    Set aSl = Application.ActiveWindow.View.Slide 'active slide
    aSl_Index = Application.ActiveWindow.View.Slide.SlideIndex 'active slide index



    ''''''''''''''''''''''''''''
    'In this section I tried to make an array of all the freeform shapes on the slide, thinking that would help.

        With aSl.Shapes

            numshapes = .Count

            'Continues if there are Freeform shapes on the slide

            If numshapes > 1 Then

                numFreeformShapes = 0

                ReDim FreeformShpArray(1 To numshapes)

                For i = 1 To numshapes


                     'Counts the number of Freeform Shapes on the Slide

                    If .Item(i).Type = msoFreeformShape Then

                        numFreeformShapes = numFreeformShapes + 1

                        FreeformShpArray(numFreeformShapes) = .Item(i).Name

                    End If

                Next


                'Adds Freeform Shapes to ShapeRange

                If numFreeformShapes > 1 Then

                    ReDim Preserve FreeformShpArray(1 To numFreeformShapes)

                    Set ShpRange = .Range(FreeformShpArray)

                    'asRange.Distribute msoDistributeHorizontally, False

                End If

            End If

        End With


 ''''''''''''''''''''''''''

            On Error Resume Next

            'Loop through all the shapes on the active slide
            For Each oSh In aSl.Shapes

                If oSh.Type = msoFreeform Then 'oSh.Type = 5

                        'If oSh.HasTextFrame Then

                            If oSh.TextFrame2.HasText Then 'results in -1

                                With oSh

                                    sTextToFind = .TextFrame2.TextRange.Characters
                                        'sTextToFind results in "Where to Begin"
                                        '.TextFrame2.TextRange.Characters results in "Learn the Lingo", which is the shape after Where to Begin.

                                End With

                            End If

                        'End If

                'If IsSafeToTouchText(oSh) = True Then

                    'With oSh.TextFrame

                        'sTextToFind = .TextRange.Characters.Text

                            'loop through slides looking for a title that matches the text box value
                            'For Each oSl In ActivePresentation.Slides

                                'If oSl.Shapes.HasTitle Then

                                    'Titl = Slde.Shapes.Title.TextFrame.TextRange <<<<< I kept getting the error here...


                        On Error Resume Next
                        Set dSl = FindSlideByTitle_Original(sTextToFind)

                        ' get the information required for the hyperlink
                        dSl_Title = dSl.Shapes.Title.TextFrame.TextRange
                        dSl_ID = dSl.SlideID
                        dSl_Index = dSl.SlideIndex

                            With oSh

                                .ActionSettings(ppMouseClick).Parent.Parent.View.GoToSlide dSl_Index, msoFalse  'Go to slide and don't reset animations

                            End With

                            ' find the text string in the body
                            'hypstart = InStr(1, sTextToFind, dSl_Title, 1)

                            'make the text a hyperlink
                            'With oSh.TextFrame.TextRange.Characters(hypstart, Len(sTextToFind)).ActionSettings(ppMouseClick).Hyperlink

                                '.SubAddress = dSl_ID & "," & dSl_Index & "," & sTextToFind

                            'End With

                    'End With

                    End If

                'End If

            Next oSh

End Sub

Public Function FindSlideByTitle_Original(sTextToFind As String) As Slide

    'Source: https://stackoverflow.com/questions/25038952/vba-powerpoint-select-a-slide-by-name

    Dim oSl As Slide

    For Each oSl In ActivePresentation.Slides
        With oSl.Shapes.Title.TextFrame
            If .HasText Then
                If UCase(.TextRange.Text) = UCase(sTextToFind) Then
                    Set FindSlideByTitle_Original = oSl
                End If
            End If
        End With
    Next

End Function
...