Results 1 to 3 of 3

Thread: Dynamically accessing properties

  1. #1
    New Member
    Join Date
    Oct 10
    Posts
    7

    Dynamically accessing properties

    Hi all. This is a VB question, but i'm using part of the Word object model to ask it.

    Lets say I have a block of code that normally I would set properties like this:

    With Selection.ParagraphFormat
    .LeftIndent = 0
    .RightIndent = 0
    .SpaceBefore = 0
    .SpaceBeforeAuto = False
    .SpaceAfter = 12
    End With

    Now lets say I have a database that has the following data in it:

    "ParagraphFormat","LeftIndent",0
    "ParagraphFormat","RightIndent",0
    "ParagraphFormat","SpaceBefore",0
    "ParagraphFormat","SpaceBeforeAuto",0
    "ParagraphFormat","SpaceAfter",12

    and I put that into variable form like

    ObjType = "ParagraphFormat"
    PropType = "LeftIndent"
    PropValue = 0

    Is it possible to have reference items dynamically with something similar to

    Selection.(ObjType).(PropType) = PropValue

    Sorry if this seems obscure. I'm trying to write an application in Word VBA where properties are stored in a database. I don't want to have to have a column for each property type if I can help it.

    Thanks in advance.
    Jeff

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 05
    Location
    Sydney, Australia
    Posts
    81,249

    Re: Dynamically accessing properties

    It can be done using Reflection, which is laborious to code and slow to execute, which is why it tends not to be used unless absolutely necessary. Here's how you might set a property of an object when you have the name of the property in a String:
    vb.net Code:
    1. Private Sub SetObjectProperty(obj As Object, propertyName As String, value As Object)
    2.     Dim objType = obj.GetType()
    3.     Dim prop = objType.GetProperty(propertyName)
    4.  
    5.     prop.SetValue(obj, value, Nothing)
    6. End Sub
    That code doesn't make allowance for a property that doesn't exist or a value of the wrong type. I'll leave those details to you.

  3. #3
    New Member
    Join Date
    Oct 10
    Posts
    7

    Re: Dynamically accessing properties

    Jim, processing time isn't an issue, since its a batch build and doesn't require That information is perfect. Thanks a ton!

    Yes, I'll have to make sure I have the proper values for all the enumerations such as "wdLineSpaceDouble" and the like which will be a pain (thank god for google) but I can manage. I just wanted to make sure my approach would work before I went down that path.

    Thanks!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •