Я создал макрос, который создает таблицы, точку питания, а затем копирует таблицы и вставляет их на слайды. Но иногда код пропускает строку, в которую я копирую эту таблицу (table.copy). Я не могу найти закономерности в этих пропусках строк. Когда я пишу эту строку несколько раз, моя программа работает отлично. В противном случае он иногда останавливается на строке, в которую он должен был вставить таблицу, и говорит: «Указанный тип данных недоступен». Затем я заменяю курсор на предыдущую строку («копировать»), и он работает ... до тех пор, пока не произойдет то же самое в следующий раз. Если у кого-то есть идея, большое спасибо!
Sub CreatePPT()
'Declare the variables
Dim newPowerPoint As PowerPoint.Application
Dim activeSlide As PowerPoint.Slide
Dim oldProduct As String
Dim Product As String
Dim MN As String 'month number
Dim Year As String
Dim Cluster As String
Dim i As Integer
Dim KPIindex As Integer
Dim table As Range
'actualisation oldProduct (to be replaced in KPI table)
oldProduct = ActiveWorkbook.Worksheets(3).Cells(28, 14)
'Select Global Slicers
Cluster = InputBox("Cluster")
MN = InputBox("Please enter month number (ex 05)")
Year = InputBox("Please enter year (ex 2018)")
KPIindex = slicerCountry(Cluster)
slicerDate MN, Year
'Create a new PowerPoint
Set newPowerPoint = New PowerPoint.Application
'Make a presentation in PowerPoint
newPowerPoint.Presentations.Add
'Loop on the products
For i = 1 To 6
'Change slicer and actualisation order type
Product = slicerProduct(i)
If i > 1 Then 'close former KPI file
Name = oldProduct & " KPI.xlsx"
Workbooks(Name).Close (False)
End If
'Open current KPI file, then reactivate working file
Filename = "C:\Users\moi\Documents\" & Product & " KPI.xlsx"
Workbooks.Open (Filename)
Windows("charlotte.xlsm").Activate
'actualisation of the europe global KPI table according to the product
Application.Goto Reference: = "KPI"
Selection.Replace What:=oldProduct, Replacement:=Product, LookAt:= _
xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
oldProduct = Product
ActiveWorkbook.Worksheets(3).Cells(28, 14) = oldProduct
'Set up KPI local table with the datas imported on KPIs sheet from the corresponding KPI file
ActiveWorkbook.Worksheets(1).Cells(63, 21) = ActiveWorkbook.Worksheets("KPIs").Cells(18, KPIindex)
ActiveWorkbook.Worksheets(1).Cells(64, 21) = ActiveWorkbook.Worksheets("KPIs").Cells(19, KPIindex)
ActiveWorkbook.Worksheets(1).Cells(68, 21) = ActiveWorkbook.Worksheets("KPIs").Cells(24, KPIindex)
ActiveWorkbook.Worksheets(1).Cells(69, 21) = ActiveWorkbook.Worksheets("KPIs").Cells(25, KPIindex)
ActiveWorkbook.Worksheets(1).Cells(73, 21) = ActiveWorkbook.Worksheets("KPIs").Cells(29, KPIindex)
ActiveWorkbook.Worksheets(1).Cells(74, 21) = ActiveWorkbook.Worksheets("KPIs").Cells(30, KPIindex)
ActiveWorkbook.Worksheets(1).Cells(75, 21) = ActiveWorkbook.Worksheets("KPIs").Cells(31, KPIindex)
'Add a new slide for the orders related to the current product (charts & tables & title & comments)
newPowerPoint.ActivePresentation.Slides.Add newPowerPoint.ActivePresentation.Slides.Count + 1, ppLayoutText
newPowerPoint.ActiveWindow.View.GotoSlide newPowerPoint.ActivePresentation.Slides.Count
Set activeSlide = newPowerPoint.ActivePresentation.Slides(newPowerPoint.ActivePresentation.Slides.Count)
activeSlide.Shapes(2).TextFrame.TextRange.Text = Product & " - Orders"
activeSlide.Shapes(1).TextFrame.TextRange.Text = "Comments"
'Copy the table of top five orders and paste it into the PowerPoint as a Metafile Picture
Set table = Range("top_five")
table.Copy
activeSlide.Shapes.PasteSpecial(DataType:=ppPasteMetafilePicture).Select
'Adjust the positioning of the table on Powerpoint Slide
activeSlide.Shapes(3).Width = 263
activeSlide.Shapes(3).Left = 230
activeSlide.Shapes(3).Top = 270
'Copy the table of HTD Orders and paste it into the PowerPoint as a Metafile Picture
Set table = Range("growth")
table.Copy
activeSlide.Shapes.PasteSpecial(DataType:=ppPasteMetafilePicture).Select
'Adjust the positioning of the table on Powerpoint Slide
activeSlide.Shapes(4).Width = 261
activeSlide.Shapes(4).Left = 230
activeSlide.Shapes(4).Top = 70
'Copy the table of KPI and paste it into the PowerPoint as a Metafile Picture
Set table = Range("ClusterKPI")
table.Copy
activeSlide.Shapes.PasteSpecial(DataType:=ppPasteMetafilePicture).Select
'Adjust the positioning of the table on Powerpoint Slide
activeSlide.Shapes(5).Width = 200
activeSlide.Shapes(5).Left = 20
activeSlide.Shapes(5).Top = 96
Next
'close the last KPI file opened
Name = oldProduct & " KPI June.xlsx"
Workbooks(Name).Close (False)
AppActivate ("Microsoft PowerPoint")
Set activeSlide = Nothing
Set newPowerPoint = Nothing
End Sub
Я видел, что это было решение для кого-то другого, но я уже проверил свои настройки макроса, и включен параметр «Доверять программный доступ к объектной модели VBA» ...
Поскольку это определенно не подходящее решение - просто скопировать и вставить десять раз подряд одну и ту же строку кода в надежде, что одна из них не будет пропущена, если бы кто-нибудь мог мне помочь с помощью инструмента «On Error GoTo», это также было бы отличным помогите, потому что я пытался написать
Set table = Range("ClusterKPI")
table.Copy
On Error GoTo 135 'where 135 is the number of the previous line
activeSlide.Shapes.PasteSpecial(DataType:=ppPasteMetafilePicture).Select
Но возникла ошибка компиляции: метка не определена.
Еще раз спасибо





Excel копирует и вставляет данные так быстро, что для переключения приложения требуется некоторое время.
Попробуйте добавить приведенный ниже код перед вставкой значений
Application.Wait(Now + TimeValue("0:00:02")) '2 represents 2 seconds
Используйте оператор With-End With, чтобы не выбирать:
вместо
activeSlide.Shapes.PasteSpecial(DataType:=ppPasteMetafilePicture).Select
activeSlide.Shapes(3).Width = 263
activeSlide.Shapes(3).Left = 230
activeSlide.Shapes(3).Top = 270
Вы можете использовать:
With activeSlide
.Shapes.PasteSpecial DataType:=ppPasteMetafilePicture
.Shapes(3).Width = 263
.Shapes(3).Left = 230
.Shapes(3).Top = 270
End With
И, возможно, встраивать application.wait не нужно