Author Topic: VBA - A 12 Steps Program (or more if need be)  (Read 2697 times)

0 Members and 1 Guest are viewing this topic.

David Hall

  • Automatic Duh Generator
  • King Gator
  • Posts: 4075
VBA - A 12 Steps Program (or more if need be)
« on: September 30, 2005, 03:18:05 PM »
I am going to try and create a 12 Step program for VBA that will highlight and give examples for some of the more common functions used in VBA so that members of TheSwamp can cut and paste right into their own modules.
« Last Edit: October 05, 2005, 12:03:12 PM by CmdrDuh »
Everyone has a photographic memory, Some just don't have film.
They say money can't buy happiness, but it can buy Bacon and that's a close second.
Sometimes the question is more important than the answer. (Thanks Kerry for reminding me)

David Hall

  • Automatic Duh Generator
  • King Gator
  • Posts: 4075
12 Steps to VBA - The Outline
« Reply #1 on: October 04, 2005, 12:44:54 PM »
This is the outline I'm working up, and additions are welcome.  Post suggestions or missing items here

12 Steps to VBA
  • 1 IDE access and VBAManager
  • 2 Public vs. Private, and Sub vs. Function
  • 3 Declaring Variables and Arrays
  • 4 Error Control, trapping, checking and CYA
  • 5 If/Then/Else For Each, While, Do While,  and Select Case
  • 6 Selection Sets - Creating, adding to and removing from, do exist
  • 7 Layers, Linetypes, Text Styles, Dim Styles
  • 8 Creating OBJ's - Lines, Circles, Text, inserting blocks/xrefs
  • 9 Changing OBJ's properties, system vars, environment vars
  • 10 Modifying OBJ's - move, copy, rotate, erase, mirror
  • 11 Save, Plot, LISP, Scripts
  • 12 Wrap up and Finish
« Last Edit: October 05, 2005, 06:11:52 PM by CmdrDuh »
Everyone has a photographic memory, Some just don't have film.
They say money can't buy happiness, but it can buy Bacon and that's a close second.
Sometimes the question is more important than the answer. (Thanks Kerry for reminding me)

David Hall

  • Automatic Duh Generator
  • King Gator
  • Posts: 4075
Step 1 - The VBA Editor
« Reply #2 on: October 05, 2005, 11:37:11 AM »
The environment where we will do our programming is the VBA IDE (Integrated Design Environment).  This document describes how to access the editor and some of the features the editor has to help you program in VBA.

After you have read the first document, this document helps you configure your editor to be a little easier to use.

Any questions you might have can be posted in this thread
Everyone has a photographic memory, Some just don't have film.
They say money can't buy happiness, but it can buy Bacon and that's a close second.
Sometimes the question is more important than the answer. (Thanks Kerry for reminding me)

David Hall

  • Automatic Duh Generator
  • King Gator
  • Posts: 4075
Step 2 - Public vs Private and Sub vs Function
« Reply #3 on: October 05, 2005, 03:39:25 PM »
The next step is to determine if you need Subroutines or Functions.  This Document discusses the uses of both.

Feel free to ask questions in this thread
Everyone has a photographic memory, Some just don't have film.
They say money can't buy happiness, but it can buy Bacon and that's a close second.
Sometimes the question is more important than the answer. (Thanks Kerry for reminding me)

David Hall

  • Automatic Duh Generator
  • King Gator
  • Posts: 4075
Step 3 - Declaring variables
« Reply #4 on: October 05, 2005, 04:39:23 PM »
To declare Variables and Arrays, we will use the Dim Statement

From the Help file
Quote
variable
A named storage location that can contain data that can be modified during program execution. Each variable has a name that uniquely identifies it within its scope. A data type can be specified or not.

Variable names must begin with an alphabetic character, must be unique within the same scope, can't be longer than 255 characters, and can't contain an embedded period or type-declaration character.

So from this, we see that our variables can be named pretty much anything we want.  There are a few guidelines and rules you must follow:
  • Less than 255 Characters - pretty easy, but opens the door for really useful names
  • Must start with Alpha Character - OK, so no Numbers for first letter
  • Cannot use PreDefined 'special' words - Dont use keywords that VBA has functions named
  • Data type should be declared - Not necessary, but better if you do

Also from the Help File
Quote
Dim [WithEvents] varname[([subscripts])] [As [New] type] [, [WithEvents] varname[([subscripts])] [As [New] type]] . . .


The Dim statement syntax has these parts:

  • WithEvents Optional. Keyword that specifies that varname is an object variable used to respond to events triggered by an ActiveX object. WithEvents is valid only in class modules. You can declare as many individual variables as you like using WithEvents, but you can't create arrays with WithEvents. You can't use New with WithEvents.
  • varname Required. Name of the variable; follows standard variable naming conventions.
  • subscripts Optional. Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax:
    [lower To] upper [, [lower To] upper] . . .
    When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.
  • New Optional. Keyword that enables implicit creation of an object. If you use New when declaring the object variable, a new instance of the object is created on first reference to it, so you don't have to use the Set statement to assign the object reference. The New keyword can't be used to declare variables of any intrinsic data type, can't be used to declare instances of dependent objects, and can’t be used with WithEvents.
  • type Optional. Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type. Use a separate As type clause for each variable you declare.

Remarks
Variables declared with Dim at the module level are available to all procedures within the module. At the procedure level, variables are available only within the procedure.  Use the Dim statement at module or procedure level to declare the data type of a variable. For example, the following statement declares a variable as an Integer.
Dim NumberOfEmployees As Integer

Also use a Dim statement to declare the object type of a variable. The following declares a variable for a new instance of a worksheet.
Dim X As New Worksheet
« Last Edit: January 16, 2006, 12:52:38 PM by CmdrDuh »
Everyone has a photographic memory, Some just don't have film.
They say money can't buy happiness, but it can buy Bacon and that's a close second.
Sometimes the question is more important than the answer. (Thanks Kerry for reminding me)

David Hall

  • Automatic Duh Generator
  • King Gator
  • Posts: 4075
Step 4 - Error Checking
« Reply #5 on: October 05, 2005, 06:12:56 PM »
in process still

IF Then Else
Quote from: Help File
Conditionally executes a group of statements, depending on the value of an expression
Syntax
All on one line:
If condition Then statements Else elsestatements

Or, you can use the block form(multi-line) syntax:

If condition Then
statements
Else
elsestatements
End If
So some examples, using the Optional ElseIf, would be
Code: [Select]
Dim Number, Digits, MyString
Number = 53    ' Initialize variable.
If Number < 10 Then
    Digits = 1
ElseIf Number < 100 Then
' Condition evaluates to True so the next statement is executed.
    Digits = 2
Else
    Digits = 3
End If

Select Case
Select Case allows you to check more conditions without nesting multiple If's
To use Select case, you test a variable against multiple conditions.  The first one that resolves True, has its statements executed, and the testing stops there.  So if A = 87

    Select Case A
        Case 23: 'In the case where A = 23
            Do something
        Case 46 'In the case where A = 46
            Do something
        Case Else:  'Catch all for any other number that A equals
            Do something else
    End Select

Error Checking
Errors are going to happen, but what do we do with them when they do occur is what is important.
Quote
Private Sub CreateLayer(ByRef Lname As String, Optional Lcolor As Integer, Optional Ltype As String)
    Dim objLayer As AcadLayer
    On Error GoTo ErrorHandler

    If DoesLayerExist(Lname) = False Then
        Set objLayer = ThisDrawing.Layers.Add(Lname)
        objLayer.color = Lcolor
        objLayer.Linetype = Ltype
    End If
    GoTo Clean_Up

ErrorHandler:

    Select Case Err
        Case -2145320939: 'In the case where the error number is XXX
            Err.Clear
            MsgBox "No color provided with this layer"
            Resume Next
        Case -2145386493: 'In the case where the error number is XXX
            Err.Clear
            MsgBox "No Linetype used W/this layer"
            Resume Next
        Case -2145386476: 'In the case where the error number is XXX
            Err.Clear
            MsgBox "You tried to use a Linetype that has not been loaded"
        Case Else:  'Catch all for any other number that gets thrown
            Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext
    End Select
Clean_Up:
    Set objLayer = Nothing
    Exit Sub
End Sub
Select Case is the best way to error check your code.  It allows you to be specific with certain error codes, or very general with the Else case.
« Last Edit: January 16, 2006, 02:33:01 PM by CmdrDuh »
Everyone has a photographic memory, Some just don't have film.
They say money can't buy happiness, but it can buy Bacon and that's a close second.
Sometimes the question is more important than the answer. (Thanks Kerry for reminding me)