我真的不知道为什么会这样:
这里是一个小小的演示包装:
' Class PPTGenPresentation
Private m_Presentation As Presentation
Public Sub Class_Initialize()
Set m_Presentation = Nothing
End Sub
Public Sub Class_Terminate()
If Not m_Presentation Is Nothing Then
m_Presentation.Close
End If
End Sub
Public Sub Initialize(ByVal presentationPath As String)
On Error GoTo Error
Set m_Presentation = Presentations.Open(presentationPath, , , msoFalse)
Exit Sub
Error:
MsgBox ("Could not open " & presentationPath)
End Sub
Public Property Get Instance() As Presentation
' After this line Class_Terminate() gets called somehow ..
Instance = m_Presentation
End Property
打开ppt后,我想通过访问属性来访问实际演示:
For Each filePath In filePaths
Set safePresentation = New PPTGenPresentation
safePresentation.Initialize (filePath)
Dim tmp As Presentation
Set tmp = savePresentation.Instance
For Each oSlide In tmp.Slides
Set oShape = oSlide.Shapes(1)
If oShape.HasTextFrame Then
If oShape.TextFrame.HasText Then
MsgBox oShape.TextFrame
End If
End If
Next
Next
但是在访问属性Instance
之后,Class_terminate
就会被调用。
我不知道为什么会发生这种事。有人能给我解释一下是什么问题吗?
发布于 2013-12-13 14:53:56
我已经在您的代码中添加了注释。
基本上,当您使用set=new
覆盖一个对象时(就像在每次后续迭代中通过For每个循环所发生的那样),从理论的角度来看,前面的对象有两种情况之一:
VBA自动导致第二个为真。当您再次使用“新建”时,第一个演示文稿将不再有任何方法引用它,因此它被清理和销毁。这就叫Class_Terminate
请注意,在没有这类代码的其他语言中,会开始导致内存泄漏(如C++)。
For Each filePath In filePaths
'Each subsequent iteration the following basically happens:
'when you set the presentation to a new one, you are effectively
'ending the previous version. So for example, the following *basically* happens:
' if not safePresentation is nothing then set safePresentation=nothing
Set safePresentation = New PPTGenPresentation
safePresentation.Initialize (filePath)
Dim tmp As Presentation
Set tmp = savePresentation.Instance
For Each oSlide In tmp.Slides
Set oShape = oSlide.Shapes(1)
Next
Next
要解决这个问题,请将Set safePresentation = New PPTGenPresentation
移到For Each
循环的上方。
发布于 2013-12-13 16:17:25
它会被调用,因为代码中有语法错误,我怀疑调用代码中有On Error Resume Next
。
Public Property Get Instance() As Presentation
' After this line Class_Terminate() gets called somehow ..
Instance = m_Presentation
End Property
生成一个错误,该错误将被简历下一步抑制,请尝试:
Public Property Get Instance() As Presentation
' After this line Class_Terminate() gets called somehow ..
Set Instance = m_Presentation
End Property
你最好不要抑制错误,当然也不要在测试的时候。
https://stackoverflow.com/questions/20568570
复制相似问题