1 / 49

Lecture 9

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.

lara
Download Presentation

Lecture 9

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture 9 Visual Basic: The er…basics

  2. 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.

  3. 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”

  4. 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.

  5. 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.

  6. 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…

  7. 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

  8. What does it look like? • Usually the development environment hides everything but the method or Subroutine you’re interested in. • Autocompletion as you type.

  9. 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.

  10. 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.

  11. 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.

  12. 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).

  13. 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.

  14. The Next Four Lectures • Language Basics; Macros • ArcObjects: Holding Stuff; UIControls • ArcObjects: Using Data; Forms • COM Objects,other ways of programming Arc; Model Builder

  15. 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.

  16. Language Basics • Code layout • Variables • Classes and Objects • Flow control

  17. 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.

  18. 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.

  19. 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.

  20. 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

  21. 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.

  22. 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.

  23. 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)

  24. 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()

  25. 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

  26. 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

  27. Flow Control • Methods in Visual Basic • Built in functions • Subs and Functions • If-Else • Case • Loops • Error Handling

  28. 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”

  29. 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”

  30. 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)

  31. 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.

  32. Calling Functions • Called thus… Dim a As B a = function(input1,input2) • For example… celsius = Temperature(fahrenheit)

  33. Flow Control • Methods in Visual Basic • Built in functions • Subs and Functions • If-Else • Case • Loops • Error Handling

  34. 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

  35. 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

  36. Flow Control: Do Loops Do WhileconditionTrue ‘Stuff Loop Do UntilconditionTrue ‘Stuff Loop

  37. Flow Control: For Loops Optional Forvar=startValToendVal [increment] ‘Stuff Next [var]

  38. Exit • To leap out of a block of code, use the Exit statement. Exit Do Exit For Exit Function Exit Sub

  39. 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

  40. 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

  41. 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.

  42. Making a Module • Insert a new Module. • Rename it. • Type a Subroutine. This then appears on the Macro list on the Tools menu.

  43. 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.

  44. 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.

  45. 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

  46. 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.

  47. 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.

  48. Summary • Make a module in the correct Project. • Write your Sub/s and Functions. • Attach the code to a GUI element.

  49. Next Lecture • Holding Stuff: The ArcObjects Framework. • Adding bespoke tools. Practical • Our first Macro

More Related