VBA How to clear object before Exit Sub within With Object statement [duplicate]

ぃ、小莉子 提交于 2021-01-29 20:40:48

问题


I have used Exit Sub within With statement to avoid Set statement in below code. Will this clear the object or is there a way to do this?

Dim FolderPathStr As String
With CreateObject("Scripting.FileSystemObject")
  If .FolderExists(FolderPathStr) = False Then
    MsgBox "Folder does not Exist"
    Exit Sub
  End If
End With

回答1:


As the comments say, VBA has automatic garbage collection. That means that when the VBA run time determines an object or variable is no longer used, it may release the object or variable.

In your example, the Scripting.FileSystemObject object can no longer be accessed once the End With statement is reached so VBA may release the object there.

Would you have assigned the created object to an object variable, then there are two ways that the object can or will be released. Example:

Sub Example

    Dim myObject As Object
    Set myObject = CreateObject("Scripting.FileSystemObject")
    '
    ' ...whatever you want to do with it...
    '
    Set myObject = Nothing    ' explicit release of the object

End Sub                       ' implicit release of the object

The explicit release of the object releases the object by programmer command. That may be usefull of a lot if work still follows where the object is no longer needed as it could decrease the resource demand of the program

The implicit release of the object occurs at the end of the Sub because the object variable ceases to exist - VBA releases the variable and release its object.



来源:https://stackoverflow.com/questions/63194333/vba-how-to-clear-object-before-exit-sub-within-with-object-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!