490 likes | 658 Views
Lecture 9. Visual Basic: The er…basics. What is it?. A high level language. Reasonably powerful. An Object Orientated language Inheritance, Classes, and Subclasses. Various levels of interpretation and compilation depending on which version. Pros.
E N D
Lecture 9 Visual Basic: The er…basics
What is it? • A high level language. • Reasonably powerful. • An Object Orientated language • Inheritance, Classes, and Subclasses. • Various levels of interpretation and compilation depending on which version.
Pros • Like AML there are default methods you can use. • You can also write your own methods/functions – which is less likely in AML. • Don’t have to write Classes, or even your own methods – fill in methods already defined. • Wizards to help with the tricky stuff. • Development environment makes writing and running easy. • Well integrated into Windows applications. • Linus Torvalds: “I personally believe that ‘Visual Basic’ did more for programming than ‘Object-Oriented Languages’ did”
Cons • Most not platform independent when compiled to binaries. Not much support outside of Windows. • Hides away stuff, so you don’t learn much about programming. • Easy to do stuff the language developers want you to do, tough to do other stuff. • Actually quite complex to build an application that works with Arc because you have to register them with the Windows registry. • Microsoft make major changes every few years.
Different Flavours • 1964 BASIC : Beginners All-purpose Symbolic Instruction Code • 1975 Microsoft BASIC, which becomes Quick BASIC or QBasic. Mainly DOS consoles. • Visual Basic 1 : Easy language for building Windows. Interpreted so slow. • 1996: Visual Basic 4 : Object Orientated • 1997: Visual Basic 5 : Compiled when distributed option. • ArcGIS currently uses VBA which is based on VB6.
Different Flavours: .Net • Latest version is VB.net. The .Net framework is… • Virtual Machine that runs any code matching a format. • A set of interfaces/protocols for interacting with networked objects and programs. • All .Net languages have the same Common Language Runtime (CLR) format. They just have slightly different syntax and IDE learning curves. The same functions are available in VB as VC++. • Because of this there have been substantial changes. The language now matches C++ with try-catches, errors, variable typing, methods etc etc. • Joy! It’s just like Java! Thank you Bill Gates! Oh happy day…
Code Based on ArcObjects framework Sub MyZoomIn() ' ' macro: MyZoomIn ' Dim pDoc As IMxDocument Set pDoc = ThisDocument Dim pEnv As IEnvelope Set pEnv = pDoc.ActiveView.Extent pEnv.Expand(0.5, 0.5, True) pDoc.ActiveView.Extent = pEnv pDoc.ActiveView.Refresh End Sub
What does it look like? • Usually the development environment hides everything but the method or Subroutine you’re interested in. • Autocompletion as you type.
Different Flavours: Macros • Macros • Visual Basic for Applications (VBA). • VBA is a subset of VB6 specifically for a particular set of Applications written in a particular way: Word, Excel, Arc. • Written in the Macro editor and Interpreted. • Arc gives you access to certain things, like the current Document (~Map) as Objects (The ArcObjects Framework). • You can then do stuff to them. • Run the macros from the Tools > Macros dialog or attach them to buttons / menus. • Can be attached to Forms.
UIControls • Controls that sit in the ArcMap GUI and have code associated with them. • Buttons • Toolbar buttons • Drop down lists • Textboxes • Slightly different to Macros, where you attach code to a button or menu. These are objects containing the code.
COM ActiveX Objects • Much more powerful. • Can be a whole application that works within Arc. • Can be a Dynamically Linked Library (DLL) that is loaded into Arc when it starts. • Written in the VB.Net or VB6 (in Visual Studio). • Compiled into binary files and need installing.
ArcEngine • Splits Arc up so you can build components into other applications. • Essentially like ArcObjects, but external. • Java version and Windows (C++/VB) version. • If you do the Java course we’ll look at a basic alternative in two weeks. • Was (still is?) MapObjects (~$5000).
Summary • Macros – basic small programs using VBA. • UIControls – Objects you can reprogram. • ActiveX components – full VB programs that run in Arc. • ArcEngine – full programs that run outside of Arc.
The Next Four Lectures • Language Basics; Macros • ArcObjects: Holding Stuff; UIControls • ArcObjects: Using Data; Forms • COM Objects,other ways of programming Arc; Model Builder
This Lecture • The language basics • Macros and toolbars • We’ll come on to how the code is stored in files a little later. For now all we need to know is that Macros are stored in a text file you can access via the Visual Basic Editor in ArcMap.
Language Basics • Code layout • Variables • Classes and Objects • Flow control
Code Layout: Subroutines • Macros are Subroutines. • Make one by typing the keyword Sub, followed by the method name. • VB will then autocomplete the code for you. Sub name () End Sub • Note that all the making of the text files containing the code, the loading and the compiling is hidden from you.
Code Layout: Declarations • You can define variables seen by all the Subs in a file at the top: Select “Declarations” from the drop down list of Subs. • Note that this list also allows you to jump to particular Subs. • The fact that there are declaration variables doesn’t stop you setting up variables in methods.
Variables: Variable Types • Declare variables as… DimnameAsType • This sets up a label of this type in memory. • Simple Types… • Integer : Whole numbers • Double: Decimals • Currency(VB6) : Fixed point numbers with 4 decimal digits. • Byte: 8 binary bits or 0-255. • String: Up to 2Gig of text. • Boolean: True or False • Date : Date and time values.
Setting and Using Variables • Simple types like these can be attached to an object of a simple type with an equals sign. This puts the value in the variable… name = 23; a = 2 + 2 b = “Eyeball Kid” c = True d = False e = 5 Print a & “ times “ & e &“ = “ & a*e Note that this gives… 4 times 5 = 20
Variables • You can also declare Variables as Variant type. In this case VBA adjusts the type as you put stuff in. Dim nameAs Variant [VB6\A] Dim nameAs Object [VB.net] Dim name [VB6\A] Typing Option Explicit in the Declarations area at the top of the code dictates you must declare variable types from then on.
Dates dateVar = “01/01/2002” dateVar = #23:55:00 PM# dateVar = “01/01/2002 23:55:00 PM” dateVar2 = Date()[VB6] ‘or Time() dateVar2 = Today()[VB.net] ‘or TimeOfDay() Dim years, months, days years = Year(dateVar – dateVar2) months = Month(dateVar – dateVar2) days = Day(dateVar – dateVar2) tomorrowplus1hour = Date() + 1 + (1/24) Integers are days, 1/24 is an hour etc.
Casting • Methods to convert one variable type to another. Dim a As Integer Dim b As Double b = CDbl(a) • The methods are… • CBool (Boolean) CByte (Byte) Ccur (Currency) • Cdate (Date) CDbl (Double) Cint (Integers) • CLng (Long) CSng (Single) CStr (String) • Cvar (Variant)
Objects and Classes • VB allows you to make Classes which define an original of a type of object. You can use this to make copies of the object. • You can then call methods or variables inside the objects. • Note that in VB6 you need to use the Set keyword DimobjectAsTypeOfClass Set object = NewTypeOfClass Set someVar = object.variableName Set someVar = object.function(inputs) object.subroutine()
Important Variable Values • Numeric variables are initiated to zero. • String variables are initiated to “”. • Variant variables are initiated to Empty. The IsEmpty(variable) method returns a true or false. • Methods that set up object variables can return a Null value that can be tested with IsNull(object). • Nothing : Used to remove the object a variable name links to. Set object = pDoc.ActiveView.Extent Set object = Nothing
ArcObjects • Arc exposes (gives you access to) the Objects and Classes that make it up. • You can then use these in applications. Sub MyZoomIn() ' ' macro: MyZoomIn ' Dim pDoc As IMxDocument Set pDoc = ThisDocument Dim pEnv As IEnvelope Set pEnv = pDoc.ActiveView.Extent pEnv.Expand 0.5, 0.5, True pDoc.ActiveView.Extent = pEnv pDoc.ActiveView.Refresh End Sub
Flow Control • Methods in Visual Basic • Built in functions • Subs and Functions • If-Else • Case • Loops • Error Handling
Standard VB functions • VB Comes with a number of Functions built in. • We looked at the conversion and date functions earlier. • Useful String functions: • Trim(String) Cuts off spaces around Strings • Dim str As String • str = “ User Name ” • str = Trim(str) str now is “User Name”
String Functions • Instr(start,searchString,searchTerm, comparison) Searches for Substrings Dim start As Integer start = Instr(1,str,”Na”,0) • Start now contains six. • Mid(String, startPosition, length) Gets Substrings str = Mid(str, start,4) • str now is “Name”
Methods in Visual Basic: Subroutines • Subroutines: do a job Subname(input As Type, a As B) ‘Code End Sub • Called thus… name (input1, a1) Callname(input1,a1)
Methods in Visual Basic: Functions • Functions: return a result by setting their name equal to it. Function name(a As B, c As D) As ReturnType ‘Do stuff name = someValue ‘return line End Function • In VB.Net you use return somevalue instead.
Calling Functions • Called thus… Dim a As B a = function(input1,input2) • For example… celsius = Temperature(fahrenheit)
Flow Control • Methods in Visual Basic • Built in functions • Subs and Functions • If-Else • Case • Loops • Error Handling
Flow Control: If IfconditionThenstatement IfconditionThen ‘Stuff End If IfconditionThen ‘Stuff Else ‘Other stuff End If Ifcondition1Then ‘Stuff ElseIf condition2Then ‘Other stuff ElseIfcondition3Then ‘Yet more stuff Else ‘Last chance End If
Flow Control: Case Statements Select Case getDay() Case 1,2,3,4 Print “Who cares” Case 5 Print “Friday!” Case Else Print “Weekend!” End Select Select Caseexpression Casevalue1 ‘Stuff Casevalue2, value3 ‘Stuff Case Else ‘Default stuff End Select
Flow Control: Do Loops Do WhileconditionTrue ‘Stuff Loop Do UntilconditionTrue ‘Stuff Loop
Flow Control: For Loops Optional Forvar=startValToendVal [increment] ‘Stuff Next [var]
Exit • To leap out of a block of code, use the Exit statement. Exit Do Exit For Exit Function Exit Sub
GoTo and Errors Sub x() On Error GoTo ErrorHandler Print (0/0) Exit Sub ErrorHandler: Print Err.Description Print Err.Number (Can use in Case statement) End Sub
Summary • We’ll now look at the actual process of writing and storing a Macro… • Making Classes • Storing Classes • Attaching Macros to the GUI. • Code layout • Variables • Classes and Objects • Flow control • Methods in Visual Basic • If-Else • Case • Loops • Error Handling
Where is the code stored? • Code is stored in Modules, Class Modules and UserForms. • Modules : A standard area for dumping code. • CoClass Modules : Define Classes you can make into Objects. • UserForms : GUIs with code attached.
Making a Module • Insert a new Module. • Rename it. • Type a Subroutine. This then appears on the Macro list on the Tools menu.
Where is VBA stored in ArcMap? • Depends on who you want to see it. • ArcMap is based on multiple templates (.mxt files). • Templates store colour schemes etc. but also VBA Projects. • You can save and load your own from the File > Save menu – just select .mxt rather than .mxd. Normal Template Project :always loaded – everyone sees this code. Project :code associated with this map. TemplateProject :code associated with a template.
Where is VBA stored in ArcCatalog? • As there’s no specific data options, ArcCatalog doesn’t have user-defined templates. • All VBA is stored in the Project associated with the default Normal.gxt template. We’ll deal largely with ArcMap in this course.
Dealing with templates • If you save templates in Arc’s /bin/templates directory they’ll appear as part of the “Open Template” dialog. • If you make folders in this directory they appear as tabs. You can start Arc with a template by setting up a Window’s shortcut with the following command line… Path\arcmap.exe Path\template.mxt
Attaching a Macro to a Toolbar. • While you can run macros from the Macro Dialog, it’s more usual to attach them to a toolbar button or menu. • Right-click the toolbar area and pick Customize. Make a new toolbar if you want. Store it in the correct template. • Find the Macro under the Commands tab, and drag it into your chosen Toolbar.
Attaching to a menu • Find the Macro Command in Customize. • Open the menu, and drag it in. • Right click to alter name and icon. • Choosing “Context Menus” from the toolbar list in Customize brings up the Context Menus. • These appear when you right-click on an item and differ depending on what and where you click. You can drag onto these as well.
Summary • Make a module in the correct Project. • Write your Sub/s and Functions. • Attach the code to a GUI element.
Next Lecture • Holding Stuff: The ArcObjects Framework. • Adding bespoke tools. Practical • Our first Macro