想要使用vba在powerpoint中查找文本并使用excel中的单元格替换文本,但不断收到错误

时间:2016-04-21 09:33:18

标签: vba excel-vba powerpoint-vba excel

我的代码的这一部分应该在powerpoint形状中找到文本并用excel中的单元格中的文本替换它:

Dim oSld As Slide
Dim oShp As Shape
Dim oTxtRng As TextRange
Dim oTmpRng As TextRange
Dim strWhatReplace As String, strReplaceText As String

 ' write find text
strWhatReplace = "xxxxx"
 ' write change text
strReplaceText = Sheet13.Range("C1").Value


        ' go during each slides
For Each oSld In ppPres.Slides
     ' go during each shapes and textRanges
    For Each oShp In oSld.Shapes
         ' replace in TextFrame
        Set oTxtRng = oShp.TextFrame.TextRange
        Set oTmpRng = oTxtRng.replace( _
        FindWhat:=strWhatReplace, _
        Replacewhat:=strReplaceText, _
        WholeWords:=True)

            Do While Not oTmpRng Is Nothing 
            Set oTxtRng = oTxtRng.Characters _
            (oTmpRng.Start + oTmpRng.Length, oTxtRng.Length)
            Set oTmpRng = oTxtRng.replace( _
            FindWhat:=strWhatReplace, _
            Replacewhat:=strReplaceText, _
            WholeWords:=True)
        Loop
    Next oShp
Next oSld

我一直收到运行时错误13,类型不匹配 - 调试突出显示'For each oShp in oSld.Shapes' 不知道我哪里出错了

2 个答案:

答案 0 :(得分:0)

这意味着VBA认为oShp的变量类型与oSld.Shapes返回的类型不同。代码看起来不错,但您可以在立即窗口中键入此内容以仔细检查代码何时停止:

?TypeName(oShp)
?TypeName(oSld.Shapes)

你应该看到一个不是Shape的类型(虽然在阅读你的代码时我看不出怎么样)。

ppPres在哪里被声明和设置?这是Presentation的类型吗?

答案 1 :(得分:0)

如果您引用了Microsoft Excel Microsoft PowerPoint对象库,则有两种类型的Shape

您似乎已标注Excel.Shape,但随后获得PowerPoint.Shape

尝试Dim oShp As PowerPoint.Shape