PowerPoint VBA在运行期间无法识别Excel表

Cit*_*naf 2 excel vba powerpoint-vba

我有一段很不错的代码,可以从Excel文件中复制一个范围并将其粘贴到PowerPoint中的activeslide上。经过数小时的尝试,将excel的范围粘贴为表格(没有图像),我发现以下代码可以成功工作。注意:myPP = PowerPoint应用程序。

myPP.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"
myPP.CommandBars.ReleaseFocus
Run Code Online (Sandbox Code Playgroud)

问题在于,当我执行宏时,将粘贴表,但是除非逐步执行代码,否则vba无法识别该表。我已经使用以下代码对此进行了测试。在执行过程中,将完全跳过代码,但在逐步执行过程中将触发该代码。

For Each shp In activeSlide.Shapes
   If shp.HasTable Then
       MsgBox shp.Name
   End If
Next
Run Code Online (Sandbox Code Playgroud)

下面是完整的代码。基本上,我只是希望将excel范围作为表格粘贴到我的Powerpoint中,并希望将该表格扩展为适合幻灯片。我愿意提出一些修改建议。谢谢你的帮助

Dim myPP as Object
Dim activeSlide as Object
Dim shp as Object

Worksheets("Sheet2").Activate
Worksheets("Sheet2").Range(Cells(1,1), Cells(4,7)).Copy
Worksheets("Sheet1").Activate

myPP.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"
myPP.CommandBars.ReleaseFocus

Dim myTable As String
   For Each shp In activeSlide.Shapes
       If shp.HasTable Then
           MsgBox shp.Name
           myTable = shp.Name
       End If
   Next

With activeSlide.Shapes(myTable)
      .Left = 23
      .Top = 105
      .Width = 650
      .Height = 375
End With
Run Code Online (Sandbox Code Playgroud)

对于ASH

Dim myPP As Object          'Powerpoint.Application
Dim myPres As Object        'Powerpoint.Presentation
Dim activeSlide As Object   'Powerpoint.Slide


Set myPP = CreateObject("Powerpoint.Application")
myPP.Visible = True
Set myPres = myPP.Presentations.Add
myPP.ActiveWindow.ViewType = 1   'ppViewSlide
Set activeSlide = myPres.slides.Add(1, 12) 'ppLayoutBlank
Run Code Online (Sandbox Code Playgroud)

A.S*_*S.H 5

问题来自以下事实:我们无法预测粘贴操作将持续多长时间以及何时结束。我们需要等待其完成。

' first let us count the shapes in the slide
Dim shapeCount As Integer: shapeCount = activeSlide.Shapes.Count
myPP.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"

Do '<~~ wait completion of paste operation
    DoEvents
Loop Until activeSlide.Shapes.Count > shapeCount

' Now, our table is the last in the shapes collection.
With activeSlide.Shapes(activeSlide.Shapes.Count)
    .Left = 23
    .Top = 105
    .Width = 650
    .Height = 375
End With
Run Code Online (Sandbox Code Playgroud)