Search notes:

VBA: Resource acquisition is initialization (RAII)

This is a simple example that tries to demonstrate resource acquisition is initialization with Visual Basic for Applications.

resource.cls

resource.cls is the class that wraps the resource. In this example, the acquired and freed resource is indicated with simple debug.print statements in the classes constructor and destructor (which happen to be named class_initialize and class_terminate in VBA):
option explicit

sub class_initialize() ' {
    debug.print "Allocating resource"
end sub ' }

sub class_terminate() ' {
    debug.print "Freeing resource"
end sub ' }
Github repository about-VBA, path: /language/classes/RAII/resource.cls

func.vb

The following module uses the requested resource by creating a new object of the resource (new operator).
Note that the function does not explicitly free the resource when it does not need it anymore (that is, when exit sub is called). Rather, the instance of the resource class goes out of scope which triggers class_terminate which takes care of freeing the resource.
Thus, the programmer can be sure that the resource is freed when the function useResource is left.
option explicit

sub main()
    useResource
end sub


sub useResource()

    dim r as resource : set r = new resource

    debug.print "try A" : if A then exit sub
    debug.print "try B" : if B then exit sub
    debug.print "try C" : if C then exit sub
    debug.print "try D" : if D then exit sub

end sub

function A as boolean
    A = false
end function

function B as boolean
    B = false
end function

function C as boolean
    C = true
end function

function D as boolean
    D = false
end function

Github repository about-VBA, path: /language/classes/RAII/func.vb

Creating the project

The following VBScript file uses the VBScript MS-Office App Creator to create an Excel project in order to run main (in func.vb):
<job>
<script language="VBScript" src="../../../VBS-MS-Office-App-Creator/create-MS-Office-app.vbs" />
<script language="VBScript">

   option explicit

   dim app
   dim xls
   set xls = createOfficeApp("excel", currentDir() & "created.xlsm")

   if xls is nothing then ' {
      wscript.echo("Could not create excel worksheet.")
      wscript.quit(-1)
   end if ' }

   set app = xls.application

   insertModule app, currentDir() & "func.vb"       , "func"    , 1
   insertModule app, currentDir() & "resource.cls"  , "resource", 2

   xls.save
   app.run "main"

   createObject("WScript.Shell").appActivate(app.caption)

</script></job>
Github repository about-VBA, path: /language/classes/RAII/create.wsf
On the command line, it must be invoked with
P:\ath\to\project> cscript .\create.wsf

Index