Поле ввода для выбора слайдов в презентации Powrpoint.(Почти сделано) - PullRequest
0 голосов
/ 14 июня 2019

Здравствуйте, все умные выглядывает там,

Я хочу выбрать некоторые Powerpointslides на основе входных данных из поля ввода, и я не могу заставить его работать. Возможно, что-то не так с тем, как я объявляю переменные. Я создал макрос, который называет Powerpointslides, и я хочу выбрать название слайдов в поле ввода с помощью VBA.

Так что в основном я хочу, чтобы поле ввода возвращало массив имен слайдов. Допустим, я хочу выбрать лист с именем США и Швеция, если я введу его в поле ввода. Это то, что я пробовал до сих пор.

Sub Select_Slides()


slides = InputBox("Insert Slide names to select")

list = Array(slides)

ActivePresentation.Slides.Range(list).Select

End Sub

Для того, чтобы он работал, должен быть массив листов с именами США и Швеции. У меня есть макрос, который создает новую Powerpoint только с выбранными слайдами. Вот почему я хочу выбрать слайды через поле ввода.

Спасибо

Ответы [ 3 ]

0 голосов
/ 14 июня 2019

Следующий макрос предложит пользователю указать одно или несколько имен слайдов, которые будут выделены точкой с запятой, и также включает в себя некоторую обработку ошибок.

Sub Select_Slides()

    Dim slideNames As String
    Dim slideNameArray As Variant
    Dim selectedSlideRange As slideRange
    Dim i As Long

    'prompt user to list slide names using a semi-colon as a separator
    slideNames = InputBox("Insert slide names to select using a semi-colon as a separator.")

    'if inputbox is empty, or user cancelled, exit sub
    If Len(slideNames) = 0 Then
        MsgBox "Inputbox is either empty, or user cancelled!", vbExclamation
        Exit Sub
    End If

    'split the names into an array
    slideNameArray = Split(slideNames, ";")

    'remove any leading or trailing spaces
    For i = LBound(slideNameArray) To UBound(slideNameArray)
        slideNameArray(i) = Trim(slideNameArray(i))
    Next i

    'assign the selected slides to a slide range
    On Error Resume Next
    Set selectedSlideRange = ActivePresentation.Slides.Range(slideNameArray)
    On Error GoTo 0

    If selectedSlideRange Is Nothing Then
        MsgBox "One or more listed slides not found!", vbExclamation
    Else
        selectedSlideRange.Select
    End If

    Set selectedSlideRange = Nothing

End Sub

Надеюсь, это поможет!

0 голосов
/ 18 июня 2019

Просто напоминание: метод Split может выполнять большую часть тяжелой работы, когда вам нужно преобразовать строку с разделителями в массив.

Sub SplitExample()

    Dim sText As String
    ' This would be your InputBox results, but for demo purposes:
    Dim aInputarray() As String
    Dim x As Long

    sText = "USA,Sweden"

    ' Split takes the text to split and the delimiter as parameters
    ' and returns a 0-based array
    aInputarray = Split(sText, ",")

    For x = LBound(aInputarray) To UBound(aInputarray)
        Debug.Print aInputarray(x)
    Next

End Sub
0 голосов
/ 14 июня 2019

Сначала вам нужно отформатировать строку, которую вернет InputBox. Я написал эту функцию под названием CreateCorrectArray, которая будет брать названия слайдов из вашей строки slides, тогда как разделитель запятых. Например, если вы хотите выбрать слайды с именами «Slide1» и «Slide4», вам необходимо ввести «Slide1, Slide4» в InputBox, чтобы функция возвращала массив («Slide1», «Slide4»).

Sub Select_Slides()

    slides = InputBox("Insert Slide names to select")

    list = CreateCorrectArray(slides)

    ActivePresentation.slides.Range(list).Select

End Sub

'' Create the array from string whereas comma separator
Function CreateCorrectArray(ByVal slides As String) As String()
    Dim indexChar As Integer
    Dim indexAr As Integer
    Dim startOfSlideName As Integer
    Dim MyArray() As String
    Dim nSlides As Integer

    '' Number of slides
    nSlides = ActivePresentation.slides.Count

    '' Array that storage the slides names
    ReDim MyArray(nSlides)


    indexAr = 1
    startOfSlideName = 1 '' start of slide name in the string "slides"

    '' Loop trough each character in "slide" string
    For indexChar = 1 To Len(slides)

        '' if the character is a comma
        If Mid(slides, indexChar, 1) = "," Then

           '' storage the slide's name in the array
           MyArray(indexAr) = Mid(slides, startOfSlideName, indexChar - startOfSlideName)

           indexAr = indexAr + 1
           startOfSlideName = indexChar + 1
        End If

        '' At the end of slides string, there will be
        '' no comma, so for this case, add the last
        '' slide name in MyArray
        If indexChar = Len(slides) Then
            MyArray(indexAr) = Mid(slides, startOfSlideName)
        End If
    Next

    CreateCorrectArray = MyArray
End Function
...