Есть ли способ проверить, отображается ли PowerPoint с использованием кода VBA? - PullRequest
0 голосов
/ 05 мая 2020

Я работаю над модулем VBA для интерактивного PowerPoint. В частности, я хотел бы, чтобы текстовое поле отображало текущее время и обновлялось каждую секунду (как часы в реальном времени) с помощью VBA. Я создал и реализовал часы очень хорошо, за исключением того, что часы не выходят из своего l oop, когда презентация заканчивается, и продолжат обновлять текстовое поле при редактировании PowerPoint вне режима презентации. Я пробовал использовать sub App_SlideShowEnd(ByVal Pres As Presentation) (https://docs.microsoft.com/en-us/office/vba/api/powerpoint.application.slideshowend), sub App_SlideShowNextSlide(ByVal Wn As SlideShowWindow) (https://docs.microsoft.com/en-us/office/vba/api/powerpoint.application.slideshownextslide) и даже надстройку под названием AutoEvents (использование показано здесь http://www.mvps.org/skp/autoevents.htm#Use), чтобы поймать конец слайд-шоу, но безрезультатно.

Итак, мой вопрос к вам: есть ли способ проверить, активно ли текущая презентация PowerPoint? Если это так, я мог бы использовать его, чтобы проверить, присутствует ли PowerPoint, вместо проверки моей логической переменной clockstate, которая позволяет часам считать или нет. Вот реализация только подсистемы часов:

Sub clock()

Do Until clockstate = False
MsgBox ActivePresentation.SlideShowWindow.View

Injury.TextFrame.TextRange.text = (Date - entryA) & ":" & Mid(CStr(Time()), 1, Len(Time()) - 3)
Defect.TextFrame.TextRange.text = (Date - entryB) & ":" & Mid(CStr(Time()), 1, Len(Time()) - 3)
Call Wait(1)
Loop

End Sub

Sub Wait(sec As Integer)

Dim temp_time As Variant
temp_time = Timer
Do While Timer < temp_time + sec
DoEvents 'this allows for events to continue while waiting for sec seconds
Loop

End Sub

Вот реализация только App_SlideShowEnd события:

Sub App_SlideShowEnd(ByVal Pres As Presentation)

clockstate = False

End Sub

И вот весь мой код вместе, если вы хотите увидеть его целиком:

Option Explicit

Dim indexA As Integer 'this variable contains the slide that Injury_Time is found on for use in the auto next slide event
Dim indexB As Integer 'this varaible contains the slide that Defect_Time is found on for use in the auto next slide event
Dim clockstate As Boolean 'this varaible dictates wether or not the clock is on and counting to save memory/processing resources.
Dim Injury As Shape 'this variable is used to reference the textbox that gets changed by the macro
Dim Defect As Shape 'this varaible is used to reference the other textbox that gets changed by the macro
Dim entryA As Date 'this holds the contents of the first entrybox on the config form so the form can be unloaded without losing the entries
Dim entryB As Date 'this holds the contents of the second entrybox on the config form so the form can be unloaded without losing the entries
Dim daysA As String 'this holds the number of days since last injury for auto-setting the textboxes in the config form
Dim daysB As String 'this holds the number of days since last defect for auto-setting the textboxes in the config form

Sub Auto_Open() 'runs on startup from AutoEvents add-in. runs the find function to locate the Macro-edited slides, then opens the config form

'declare clockstate as false until it is  true and turned on
clockstate = False

'assign values the global Injury and Defect variables
Call Find

'try calling the name fields (need to assign it to a variable to try it). If Injury and Defect were found, then nothing happens. Otherwise it moves the the Not_Found label
On Error GoTo Not_Found

'setup daysA and daysB
daysA = Left(Injury.TextFrame.TextRange.text, Len(Injury.TextFrame.TextRange.text) - 8)
daysB = Left(Defect.TextFrame.TextRange.text, Len(Defect.TextFrame.TextRange.text) - 8)

'assign default values to the Config boxes
Config.TextBox1.Value = Date - daysA
Config.TextBox2.Value = Date - daysB

'show config
Config.Show

Exit Sub

'error messaging for if the textbox assignments were not found
Not_Found:
MsgBox "Error: The Macro-edited textbox(es) were not found! This is likely due to the most recent editing preformed on this Powerpoint. Please revert the changes, create a new textbox with the name """"Injury_Time"""" or """"Defect_time"""" (whichever is missing), contact your local VBA expert, or read the Documentation for help."

End Sub

Sub Find() 'locates the textbox that the global variables Injury and Defect are supposed to represent

'use a 2D for loop to iterate through each slide and it's shapes
Dim i As Integer
Dim j As Integer
For i = 1 To ActivePresentation.Slides.Count
For j = 1 To ActivePresentation.Slides(i).Shapes.Count

If StrComp(ActivePresentation.Slides(i).Shapes(j).Name, "Injury_Time") = 0 Then
Set Injury = ActivePresentation.Slides(i).Shapes(j)
indexA = i
End If

If StrComp(ActivePresentation.Slides(i).Shapes(j).Name, "Defect_Time") = 0 Then
Set Defect = ActivePresentation.Slides(i).Shapes(j)
indexB = i
End If

Next j
Next i

End Sub

Sub Save() 'saves the contents of the config form to the global varaibles entryA and entry B then unloads the form to save memory

'save the contents of the config form so we can unload it to save memory
entryA = Config.TextBox1.Value
entryB = Config.TextBox2.Value

'unload the form to save memory
Unload Config

End Sub

Sub Auto_ShowBegin() 'starts the clock for the timers when the show starts

'start clock
clockstate = True
Call clock

End Sub

Sub clock()

Do Until clockstate = False
MsgBox ActivePresentation.SlideShowWindow.View

Injury.TextFrame.TextRange.text = (Date - entryA) & ":" & Mid(CStr(Time()), 1, Len(Time()) - 3)
Defect.TextFrame.TextRange.text = (Date - entryB) & ":" & Mid(CStr(Time()), 1, Len(Time()) - 3)
Call Wait(1)
Loop

End Sub

Sub Wait(sec As Integer)

Dim temp_time As Variant
temp_time = Timer
Do While Timer < temp_time + sec
DoEvents 'this allows for events to continue while waiting for sec seconds
Loop

End Sub

Sub App_SlideShowEnd(ByVal Pres As Presentation)

clockstate = False

End Sub

Sub Auto_Close() 'this is run by the AutoEvents add-in. It displays an informative message when the powerpoint is closed with instructions for the next time the powerpoint is opened

'prevent clock from running after program is closed
clockstate = False

'message to configure the powerpoint when it is opened again
MsgBox "Thank you for using this Macro-Enabled PowerPoint!" & vbCrLf & vbCrLf & "Next time the PowerPoint is opened, you will be asked to re-enter the dates of the most recent injury and quality defect."

End Sub

Спасибо за вашу помощь и 4 мая пребудет с вами!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...