逐步执行我的代码,运行我的代码会给出一个"方法' ShapeRange'对象'选择'失败"错误信息

时间:2015-06-23 12:57:52

标签: vba excel-vba powerpoint-vba excel

单步执行我的代码工作,它完全符合我的要求(从各种表格,文本框和Excel中的图像创建一个幻灯片幻灯片)。但运行代码并不起作用。我并不认为这与时间有关,因为我在该范围内粘贴后包含一段时间停顿。当代码进入" newpowerpoint.activewindow.selection ..."我得到一个"方法' ShapeRange'对象'选择'失败"错误信息。

非常感谢任何帮助。

谢谢!

Sub CreatePowerPoint()

    Worksheets("2 Source of Change and Switchi").Select

    Dim newPowerPoint As PowerPoint.Application
    Dim activeSlide As PowerPoint.Slide
    Dim cht As Excel.ChartObject

    On Error Resume Next
    Set newPowerPoint = GetObject(, "PowerPoint.Application")
    On Error GoTo 0

    newPowerPoint.Visible = True

    newPowerPoint.ActiveWindow.View.GotoSlidenewPowerPoint.ActivePresentation.Slides.count 
    Set activeSlide = newPowerPoint.ActivePresentation.Slides(newPowerPoint.ActivePresentation.Slides.count)


 '######################The Code below Copies and Pastes in My Values#####################

        Worksheets("3 Switching details – Actual v").Select


        ActiveSheet.Range(Range("D51"), Range("D51").End(xlDown)).Copy
        newPowerPoint.CommandBars.ExecuteMso ("PasteExcelTableSourceFormatting")
        Application.Wait (Now + TimeValue("0:00:01"))

        newPowerPoint.ActiveWindow.Selection.ShapeRange.Left = 640

end sub

3 个答案:

答案 0 :(得分:0)

我已经使用此代码解决了问题。似乎需要某种中断来正确运行代码。

    With Application.ActiveWindow.Selection
        MsgBox "Click ok"
    End With

答案 1 :(得分:0)

Application.Wait不可靠,但是你正处于正确的轨道上,因为它是一个"时间"问题。

ExecuteMso是一个异步任务,问题就出现了,因为代码的 next 行在 ExcecuteMso方法完成之前尝试执行 (从剪贴板复制/粘贴经常会遇到同样的错误)。 So you should be able to avoid this with DoEvents, in a loop while checking the number of shapes on the slide has been incremented

我建议在循环中使用Sleep函数来最小化CPU使用率,只需在模块的顶部声明它,如:

Private Declare Sub Sleep Lib "kernel32" (ByVal lngMilliSeconds As Long)

然后你的DoEvents循环如下:

ActiveSheet.Range(Range("D51"), Range("D51").End(xlDown)).Copy
activeSlide.Select  ' <~~ This may not be necessary, but added just in case.

Dim shapeCount as Long: shapeCount = activeSlide.Shapes.Count
newPowerPoint.CommandBars.ExecuteMso ("PasteExcelTableSourceFormatting")

Do
    Sleep 100
    DoEvents
Loop Until (activeSlide.Shapes.Count = shapeCount + 1)

' get rid of this next line and work with the slide/shape directly:
' XXX newPowerPoint.ActiveWindow.Selection.ShapeRange.Left = 640

activeSlide.Shapes(shapeCount+1).Left = 640

答案 2 :(得分:-1)

最终使用一个单独的基于powerpoint的宏来解决,该宏定位了表