VBA: Why Use Properties Instead of Subroutines or Functions?

前端 未结 4 491
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-19 11:04

Why do we need to use property Let, Get and Set in a VBA class when we can simply pass and return our arguments using subroutines or f

4条回答
  •  有刺的猬
    2021-01-19 11:41

    You don't need to ... for 90% of all applications standard VBA is just right. Using classes you have more "logical control" over your code.

    Suppose you have a function Function IsUnique(MyArg as String) as Boolean that looks up a table of persons with a name passed in MyArg and returns TRUE if the name is not found in the table. Nothing prevents you for instance to call this function and pass the string of the favourite vegetable the user chose. You will still get a syntactically correct program, despite the fact that this call will always return TRUE because vegetables are stored somewhere else in this application.

    Now suppose you have a class PersonClass containing functions (=property) Name and IsUnique()

    Your code finally you would maybe like this

    Dim MySpouse as PersonClass
        Set MySpouse = New PersonClass
        MySpouse.Name = "Fanny Hill"
        If MySpouse.IsUnique() Then
            MySpouse.Insert
        End If
    

    What seems like an overkill really encapsulates the code blocks, functions and variables pertaining to a Person (here called methods and properties) into a class and make it more obvious to your code what you are doing with a variable that makes use of that class template (aka. an instance of that class)

    Typical example: IP address arithmetic ..... (add IP's, find base or broadcast addresses, convert between various mask notations, check two ranges for overlap, find net mask sourrounding two or more IP-@es etc. etc. etc.) needed in a dozen of applications: write the class module once, and once tested you can easily reuse it.

    Another advantage with classes is that when entering the code in the VBA editor, the code completion tells you exactly what you can do with a class (i.e. all properties and methods are presented in a dropdown list) - a comfort you don't have with procedures and functions (they only tell you the argument names and types)

    Enough?

提交回复
热议问题