【问题标题】:ppt vba multiple slide selection macro errorppt vba多张幻灯片选择宏错误
【发布时间】:2022-06-10 22:18:29
【问题描述】:

当在输入框中输入多个 PowerPoint 幻灯片编号(例如:3、5、6)时,我想创建一个宏选择输入编号的幻灯片,但出现错误。

Sub test()

Dim strresponse2 As String
Dim iresponse2 As String
strresponse2 = InputBox("page number" & vbCr & "ex) 2,4,11,5")

If IsNumeric(strresponse2) Then
iresponse2 = strresponse2
End If

ActiveWindow.Selection.Unselect
ActivePresentation.slides.Range(Array(iresponse2)).Select
'error here
'How to fix it so it doesn't get an error

'ActivePresentation.Slides.Range(Array(2, 4, 11,5)).Select
'no error

End Sub

【问题讨论】:

  • 您想在输入框中输入类似2, 4, 5 的内容并希望选择幻灯片 2、4 和 5?
  • 是的,我想要....

标签: vba input range powerpoint selection


【解决方案1】:

这里有几个问题。
a) 如果输入2, 4, 5IsNumeric(strresponse2) 的检查将失败,因为该函数试图将整个字符串转换为一个单个数字。

b) Array(iresponse2) 不会将字符串转换为数组(3 个数字)。它将单个字符串 2, 4, 5 转换为具有 1 个(不是 3 个)成员的字符串数组。
在您的情况下,您可以使用 Split-function 将输入字符串拆分为字符串数组。

c) 如果您想按数字访问幻灯片,输入需要是数字类型,而不是字符串(即使字符串包含数字)。您需要将字符串数组转换为数值数组(如果您将字符串或字符串数​​组作为参数传递,VBA 将查找具有 name 的成员,而不是 index em>)。

查看以下代码并检查它是否满足您的需求 - 它只测试了一半(因为我没有可用的 Powerpoint VBA,只有 Excel,但原理是一样的)

Dim answer As String
answer = InputBox("page number" & vbCr & "ex) 2,4,11,5")
Dim pagesS() As String

pagesS = Split(answer, ",")                 ' Split the answer into an array of strings.
ReDim pagesN(0 To UBound(pagesS)) As Long   ' Create an empty numeric array
Dim countS As Long, countN As Long 
For countS = 0 To UBound(pagesS)            ' Loop over all strings
    If IsNumeric(pagesS(countS)) Then       ' String is Numeric
        Dim pageNo As Long
        pageNo = Val(pagesS(countS))        ' Convert string to number
        If pageNo > 0 And pageNo <= ActivePresentation.slides.Count Then
            pagesN(countN) = pageNo         ' When number is within valid range, copy it 
            countN = countN + 1             ' Count the number of valid page numbers
        End If
    End If
Next countS

If countN > 0 Then                          ' At least one number found
    ReDim Preserve pagesN(0 To countN - 1)  ' Get rid of unused elements
    ActivePresentation.Slides.Range(pagesN).Select    
End If

【讨论】:

    猜你喜欢
    • 2023-02-10
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 2011-02-27
    相关资源
    最近更新 更多