ENGG1811 VBA Reference Card
Total Page:16
File Type:pdf, Size:1020Kb
Part A ENGG1811 VBA Reference Card VBA Language Structure ' comment starts with a single quote Examples: Editor Access and Setup ' (and is ignored by the VB system) Dim longitude As Double Developer tab, Visual Basic identifiers are names you give to things like Dim numCells As Integer button. Starts the VBE. variables and procedures. They start with a Dim e As Double ' surface roughness letter, followed by any number of letters, digits Shortcut is Alt-F11 . Dim stressMildSteel As Double or underscores (_). Select Tools – Options menu. First data types include Integer , Long (integer with Procedures few options should be like this: wider range), Double (for normal calculations), Only two types, subprograms and functions. String , Boolean and Variant (= any type). Sub name (parameter-list ...) number formats include integer, decimal or End Sub scientific (also hexadecimal prefixed by &H ) Function name (parameter-list ...) As type string literals are enclosed in double quote name = ... ' assign result to func name characters, type two of them to represent a End Function double quote symbol: "He said, ""Hi!""" . Procedures contain local variable declarations Others are according to preference, including font each module consists of optional constant (normally occur first), and statements. in Editor Format (Consolas, Fixedsys are better than definitions, optional variable declarations, then Courier). procedures. parameter-list is a comma-separated list of local variables associated with the arguments passed to VBE Layout Declarations the procedure. Simplest format is Top left: Project Explorer. Constant definitions are of the form name As type Top right: edit window, one per object being edited. Const name = value A subprogram with no parameters is called a Bottom right: Properties window, F4 to unhide. where name is by convention ALL_CAPS and value is macro , and can be initiated by the user ( Alt-F8 ). Bottom right: Immediate window ( Debug.Print a literal or constant expression, for example: See also Parameters and Procedure Calls overleaf. Const ROW_START = 4 ' first data row destination), Ctrl-g to unhide. Procedure Conventions Const PLANCK = 6.626068e-34 'in J s Workbook objects Subprograms perform general tasks, should be Variable declarations are of the form Sheets , for related event procedures and controls. named using a verb phrase in Title Case (for Dim name As type example, ProcessCells . Workbook , event procedures open/close etc. or Functions should just calculate and return a Modules , where most of the VBA resides; Insert – Dim name1 As type1, name2 As type2, ... value, not change the workbook directly. Their Module to create, rename using the Properties names should be nouns or noun phrases, such as window. Variable names may be simple algebraic ( x, k), or indicate counting purpose (row , col ), or hold Pythagoras, LastCell, IsEmpty, significant values, using initial lower case but then RelativeBearing. Title Case (wordsJoinedWithInitialCaps). GW 1209 1 Formatting Conventions (Rules) Selection Statements Iteration Statements Always indent lines that belong to an outer If Boolean-expression Then Set variable var (usually Integer or Long) to each structure, such as procedure contents and statement element of arithmetic progression: Else selected or iterated statements. optional For var = start To finish Step amount statement Leave an empty line before each group of statements optional End If related statements. Next var Chained form: Use a comment before each procedure, before a Continue as long as Boolean-expression is true: If Boolean-expression Then statement that does something non-obvious and While Boolean-expression statement on important variable declarations. statements ElseIf Boolean-expression Then repeat as Long lines should be split by inserting a space, Wend statement needed underscore and Enter, increase indent by half. Also general form (not required for ENGG1811) : Else optional Assignment Statement statement Do ... Loop with Exit Do and/or While conditions Statements perform actions by changing the End If at either end. program state. Simplest is assignment: A single expression can be matched this way (not Parameters and Procedure Calls variable = expression required for ENGG1811) : Each parameter is a local variable, initialised from expression combines literals, named constants, Select Case expression the corresponding argument. variables and function calls, combined using Case value1 ByVal prefix means copy argument value only operators with this precedence: statements ByRef prefix means associate argument variable (if ( ) parentheses Case value1, value2, ... it is a variable) with parameter, this is default. ^ exponentiation statements Example: + – unary: sign operators Case value1 To value2, ... * / multiplication, division Sub DoIt(ByVal count As Integer , _ statements \ integer division ByRef result As Double) Case Is > value ' or any comparison Mod remainder If parameter names are known, can associate in any statements + – binary: add, subtract order using the := notation: & string concatenation Case Like pattern DoIt result:=myAnswer, count:=22 = <> < > <= >= comparisons statements Like Functions always require parentheses around Case Else ' if no match, optional Not And Or Xor Boolean operators arguments (if any), subprograms don’t, but can be statements patterns: forced with the Call statement: Like End Select * string of any length Call DoIt(22, myAnswer) each of these Early exit from procedure: [abcx-z] any single character DoIt 22, myAnswer is equivalent If exception-condition Then [!xyzE-G] any char except these to the above # digit = [0-9] Exit Function ' or Exit Sub ? any single character End If GW 1209 2 Excel Objects Object Variables Part B Hierarchy Can declare variables of specific or generic object Other Shape methods (all return a shape): Application types: AddLine( beginX, beginY, endX, endY ) ActiveWorkbook Dim rng As Range AddTextBox( orientation, left, top, _ ActiveSheet Dim wks As Worksheet width, height ) ActiveCell Dim obj As Object BuildFreeform see VBA Drawing document. Most common objects are ranges: Must use the Set keyword when assigning object Shape properties include Line , Fill ; use these to variables (because the var “points” to the object). ActiveSheet.Cells( row ,column ) change appearance: Set rng = ActiveSheet.Columns(5) ActiveSheet.Range( name ) ' "max" etc With shp.Line ActiveSheet.Range( address ) ' "A4" etc Collections .Weight = 1.5 Selection ' created by .Select Group (usually related) objects under a single name .DashStyle = msoLineDashDot .Forecolor.RGB = _ Objects have properties (attributes, some of which Can be indexed by position (1.. n) or name can be set), and methods (associated procedures). ActiveWorkbook.Sheets.Add _ RGB(128,0,0) ' dark red Notation is the same: after:=Sheets(3) End With object .property used in an expression ActiveWorkbook.Sheets("Temp").Delete With shp.Fill object .property = newvalue For Each wks In ActiveWorkbook.Sheets .Forecolor.RGB = vbYellow object .method arguments ... if a subprogram Debug.Print wks.Name .Transparency = 0.5 ' translucent object .method (arguments ...) if a function Next wks .Visible = True ' False = hide End With Range properties include ActiveSheet.Shapes Collection Value (default if omitted) Formula Represent drawing objects, coords are X and Y Colours Interior Font (down is positive) in pixels (approximately). Define Long constants, or use the RGB function. Borders NumberFormat Dim shp As Shape If you know the hexadecimal code as used on web Range methods include Set shp = _ pages, can also create meaningful Consts: ClearContents AutoFit ActiveSheet.Shapes.AddShape( type , _ web : #00CC99 = RGB(0,204,153) FillDown Merge Offset(row, col) left, top, width, height ) VBA: Const BLUE_GREEN = &H99CC00 With Statement type includes many predefined constants such as Note the reversed red and blue order. Can factorise common prefix object reference: msoShapeRectangle, msoShapeOval Built-in constants: vbBlack, vbWhite, msoShapeRightArrow, msoShapeHeart With ActiveSheet.Cells(1,4).Interior vbRed, vbGreen, vbBlue, (see MsoAutoShapeType in Excel Help) .Pattern = xlSolid vbCyan, vbMagenta, vbYellow. other arguments define rectangular bounding box. .Color = RGB(100,50,100) ' purple End With GW 1209 3 Standard Functions VBA Examples Notes Use Excel Help for more info. Function to calculate Pythagorean distance given the Here num is a Double or Integer, i is an integer, differences in X and Y values: str is a string, a is an angle in radians. Function Pythag(xDiff As Double , _ Conversions: yDiff As Double ) As Double Int( num ), Fix( num ), Round( num ,i) Pythag = Sqr(xDiff ^ 2 + yDiff ^ 2) Abs( num ), Val( str ), CStr( num ), End Function CInt( str ) Real mathematics: Snippet to process column in variable col : Sqr( num ) (square root) Dim row As Integer Exp( num ), Log( num ) (both base e, not 10) Trigonometry: row = ROW_START Sin( a), Cos( a), Tan( a) While Activesheet.Cells(row,col) <> "" Atn( num ) (arctangent) ' do something with the cell Others: row = row + 1 IsNumeric( str ) (looks like a number?) Wend RGB( red,green,blue ) (integer colour values) Rnd() (random number 0..1) Subprogram calculating two values, passed back to the caller Functions used in formulas: using ByRef parameters. Cartesian to polar conversion: WorksheetFunction. functionname (... ) Sub Polar(x As Double , y As Double , _ ByRef mag As Double , _ Error Codes and possible causes ByRef angle As Double ) 6: Overflow : calculated integer value is too large (> 32767) or too small (< –32768) mag = Pythag(x, y) 13 Type mismatch : expression mixes up numbers angle = WorksheetFunction.Atan2(x, y) and non-numeric values ' Atan2 works for x=0, Atn doesn’t 438 Object doesn’t support this property or method : End Sub you may have misspelled something after a dot, such as Activesheet. Culls (row,col) 1004 Unable to get the property [...] of the WorksheetFunction class : probably incorrect argument such as Asin with arg > 1 GW 1209 4 .