【发布时间】:2015-07-05 17:26:17
【问题描述】:
如果有人能提供以下帮助,我将不胜感激。以下代码从 MS Excel 中复制一个范围并将其粘贴到 MS PowerPoint 中。此外,还有一个循环遍历工作簿的所有工作表并应用相同的复制和粘贴公式。但是,当循环到达最后一个工作表时,我正在努力如何“关闭”循环。在代码的末尾,当我选择调试时,我得到一个运行时错误“91”:对象变量或未设置块变量,突出显示sh(ActiveSheet.Index + 1).Select。
Sub CreateDeck()
Dim WSheet_Count As Integer
Dim I As Integer
Dim Rng As Excel.Range
Dim PPTApp As PowerPoint.Application
Dim myPPT As PowerPoint.Presentation
Dim mySlide As PowerPoint.Slide
Dim myShapeRange As PowerPoint.Shape
Dim sh As Worksheet
'Set WSheet_Count equal to the number of worksheet in the active workbook
WSheet_Count = ActiveWorkbook.Worksheets.Count
'Around the world: The Loop
For I = 1 To WSheet_Count
'Copy Range from excel
Set Rng = ThisWorkbook.ActiveSheet.Range("A1:A2")
'Creat Instance for PowerPoint
On Error Resume Next
'Check if PowerPoint is open
Set PPTApp = GetObject(class:="PowerPoint.Application")
'Clear the error between errors
Err.Clear
'Open PowerPoint if it is not open
If PPTApp Is Nothing Then Set PPTApp = CreateObject(class:="PowerPoint.Application")
'Handle if PowerPoint cannot be found
If Err.Number = 429 Then
MsgBox ("PowerPoint couldn't be found, aborting")
Exit Sub
End If
On Error GoTo 0
'Make PowerPoint Visible and Active
PPTApp.Visible = True
PPTApp.Activate
'Create New PowerPoint
If PPTApp Is Nothing Then
Set PPTApp = New PowerPoint.Application
End If
'Make New Presentation
If PPTApp.Presentations.Count = 0 Then
PPTApp.Presentations.Add
End If
'Add Slide to the presentation
PPTApp.ActivePresentation.Slides.Add PPTApp.ActivePresentation.Slides.Count + 1, ppLayoutBlank
PPTApp.ActiveWindow.View.GotoSlide PPTApp.ActivePresentation.Slides.Count
Set mySlide = PPTApp.ActivePresentation.Slides(PPTApp.ActivePresentation.Slides.Count)
'Copy Excel Range
Rng.Copy
'Paste to PowerPoint and Position
mySlide.Shapes.PasteSpecial DataType:=ppPasteEnhancedMetafile
Set myShapeRange = mySlide.Shapes(mySlide.Shapes.Count)
'Set position
myShapeRange.Left = 0
myShapeRange.Top = 0
myShapeRange.Height = 450
'Clear the Clipboard
Application.CutCopyMode = False
'Next Worksheet tab
sh(ActiveSheet.Index + 1).Select
Next I
End Sub
【问题讨论】: