VBA Tip: Using the With Statement

The With statement allows for specifying members of an object or user-defined type in a more efficient and easier to read format. Each With statement requires an End With statement to close the block. An example of the with statement is shown below.

Dim myCollection As Collection
Set my Collection = New Collection
 
' Standard assignment
myCollection.Add = 5
myCollection.Add = 10
myCollection.Add = 15
 
'Assignment using With statement
With myCollection
    .Add = 5
    .Add = 10
    .Add = 15
End With
 
With CadInputQueue
    .SendKeyin "lv=default"
    .SendKeyin "co="
    .SendKeyin "wt=1"
    .SendCommand "place smartline"
End With

With statements can also be nested for even greater efficiency

' MicroStation text element example
With myText
    .Text = "This is a test"
     
    ' The TextStyle object is a member of the
    ' text element object
    With .TextStyle
        .Height = 3
        .Width = 3
    End With
End With

Rod Wing

Rod is the Senior Systems Analyst at EnvisionCAD and has extensive experience in GIS, cartography, plotting, scanning, raster editing/manipulation, publishing, and file/data translations. He instructs MicroStation classes ranging from fundamentals to advanced.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *