要获取 Excel 范围并将其粘贴到 PowerPoint 应用程序中,需要将该过程分解为几个不同的部分。查看您的代码,我们可以将其分解为以下组件:
- 创建一个 PowerPoint 实例。
- 制作幻灯片和演示文稿。
- 创建对要导出的范围的引用,然后复制它。
- 将形状与所需尺寸对齐。
- 最后,从内存中释放对象。
我假设您希望将此代码保留为后期绑定,但您的代码中也有一些部分会导致问题,因为您将其视为在早期绑定中编写的。
另外,我有一个关于这个主题的 YouTube 视频,所以如果您想要进行更复杂的粘贴或使用多个 Excel 范围,请随时观看该系列。
播放列表链接:
https://www.youtube.com/playlist?list=PLcFcktZ0wnNlFcSydYb8bI1AclQ4I38VN
第一部分:声明变量
在这里,我们将在脚本中创建我们需要的所有变量。
'Declare PowerPoint Variables
Dim PPTApp As Object
Dim PPTPres As Object
Dim PPTSlide As Object
'Dim Excel Variables
Dim ExcRng As Range
第二部分:创建一个新的 POWERPOINT 实例
这将创建一个新的 PowerPoint 应用程序,使其可见并使其成为活动窗口。
'Create a new PowerPoint Application and make it visible.
Set PPTApp = CreateObject("PowerPoint.Application")
PPTApp.Visible = True
PPTApp.Activate
第三部分:创建新的演示文稿和幻灯片
这将向 PowerPoint 应用程序添加一个新演示文稿,在演示文稿中创建一个新幻灯片并将布局设置为空白布局。
'Create a new Presentation
Set PPTPres = PPTApp.Presentations.Add
'Create a new Slide
Set PPTSlide = PPTPres.Slides.Add(1, 12) '<<< THIS 12 MEANS A BLANK LAYOUT.
第四部分:创建对 EXCEL 范围的引用并复制它
这将设置对我们要复制和复制的 Excel 范围的引用。
'Set a reference to the range
Set ExcRng = Range("B1:J31")
'Copy Range
ExcRng.Copy
第四部分:在幻灯片中粘贴为对象
这会将范围粘贴到幻灯片中并设置对它的引用。
'Paste the range in the slide
SET PPTShape = PPTSlide.Shapes.PasteSpecial(10) '<<< 10 means OLEOBJECT
第五部分:对齐形状
这将选择形状并设置它的尺寸。
'Select the shape.
PPTSlide.Shapes(PPTSlide.Shapes.Count).Select
'Set the Dimensions of the shape.
With PPTApp.ActiveWindow.Selection.ShapeRange
.Top = 65
.Left = 7.2
.Width = 700
End With
第六部分:从内存中释放对象
这将从内存中释放对象。
'Erase Objects from memory.
Set PPTApp = Nothing
Set PPTSlide = Nothing
Set PPTShape = Nothing
总的来说,这就是您的代码现在的样子:
Sub ExportRangeToPowerPoint_Late()
Dim PPTApp As Object
Dim PPTPres As Object
Dim PPTSlide As Object
Dim PPTShape As Object
Dim ExcRng As Range
'Create a new instance of PowerPoint
Set PPTApp = CreateObject("PowerPoint.Application")
PPTApp.Visible = True
PPTApp.Activate
'Create a new Presentation
Set PPTPres = PPTApp.Presentations.Add
'Create a new Slide
Set PPTSlide = PPTPres.Slides.Add(1, ppLayoutBlank)
'Set a reference to the range
Set ExcRng = Range("B1:J31")
'Copy Range
ExcRng.Copy
'Paste the range in the slide
Set PPTShape = PPTSlide.Shapes.PasteSpecial(10)
'Select the shape.
PPTSlide.Shapes(PPTSlide.Shapes.Count).Select
'Set the Dimensions of the shape.
With PPTApp.ActiveWindow.Selection.ShapeRange
.Top = 65
.Left = 7.2
.Width = 700
End With
'Erase Objects from memory.
Set PPTApp = Nothing
Set PPTSlide = Nothing
Set PPTShape = Nothing
End Sub