VBA复制范围从excel到powerpoint

时间:2018-04-30 14:52:46

标签: excel-vba powerpoint-vba vba excel

我正在尝试从excel复制特定范围并将其作为图片以pp格式过去。我将来自各种在线资源的以下代码拼凑在一起,并在运行PowerPointApp.WindowState = 2时继续获得运行时91错误(对象变量或未设置块变量)。

如何解决此错误,并在将来避免使用它?

首先我成功运行

    Private Sub OpenPowerpoint()

        Dim PPT As PowerPoint.Application
        Set PPT = New PowerPoint.Application

        PPT.Visible = True
        PPT.Presentations.Open Filename:="C:\Users\aofarrell\Desktop\CYB\Weekly Pack Update - Template.pptx"
        PPT.ActivePresentation.Slides(2).Select

    End Sub

然后我尝试运行

 Private Sub CopyToPowerPoint()

            Dim rng As Range
            Dim PowerPointApp As Object
            Dim mySlide As Object
            Dim myShape As Object


        'Copy Range from Excel

            Set rng = ThisWorkbook.Sheets("Triggers").Range("B6:Z33")

        'Copy Excel Range
            rng.Copy

        'Paste to PowerPoint and position
            PowerPointApp.WindowState = 2 'ERROR OCCURS HERE
            mySlide.Shapes.PasteSpecial DataType:=0
            Set myShape = mySlide.Shapes(mySlide.Shapes.Count)

        'Set position:
            myShape.Left = 20
            myShape.Top = 70
            myShape.Width = 675
            myShape.Height = 400

        'Clear The Clipboard
            Application.CutCopyMode = False
            Application.Wait (Now + TimeValue("00:00:01"))

        End Sub

1 个答案:

答案 0 :(得分:2)

嗯......首先,您需要定义Object的{​​{1}}类型。您PowerPointApp的具体对象是什么。还要记住局部变量在Sub / Function的末尾被销毁,所以你可能需要一些模块级变量/对象:

mySlide

(另外:如果我将图像从Excel复制到PowerPoint,我通常会使用Option Explicit Private PPT As PowerPoint.Application Private PPT_pres As PowerPoint.Presentation Private Sub OpenPowerpoint() Set PPT = New PowerPoint.Application PPT.Visible = True Set PPT_pres = PPT.Presentations.Open(FileName:="C:\Users\aofarrell\Desktop\CYB\Weekly Pack Update - Template.pptx") PPT_pres.Slides(2).Select End Sub Private Sub CopyToPowerPoint() If PPT Is Nothing Then Exit Sub If PPT_pres Is Nothing Then Exit Sub Dim rng As Range Dim mySlide As Object Dim myShape As Object Set mySlide = PPT_pres.Slides(2) 'Copy Range from Excel Set rng = ThisWorkbook.Sheets("Triggers").Range("B6:Z33") 'Copy Excel Range rng.Copy 'Paste to PowerPoint and position PPT.WindowState = 2 mySlide.Shapes.PasteSpecial DataType:=0 Set myShape = mySlide.Shapes(mySlide.Shapes.Count) 'Set position: myShape.Left = 20 myShape.Top = 70 myShape.Width = 675 myShape.Height = 400 'Clear The Clipboard Application.CutCopyMode = False Application.Wait (Now + TimeValue("00:00:01")) End Sub 而不是Range.CopyPicture xlPrinter根据您的屏幕分辨率更改图像的大小)