Presentation is loading. Please wait.

Presentation is loading. Please wait.

By : Jonthy L. Cabatuan 1WRITING A CODE.  The integral part of a programming language is the programming itself.  Code Window  is a turbo-charged text.

Similar presentations


Presentation on theme: "By : Jonthy L. Cabatuan 1WRITING A CODE.  The integral part of a programming language is the programming itself.  Code Window  is a turbo-charged text."— Presentation transcript:

1 By : Jonthy L. Cabatuan 1WRITING A CODE

2  The integral part of a programming language is the programming itself.  Code Window  is a turbo-charged text editor with many productivity tools built in.  is a place where all the commands that constitute a form, or a control are located.  is also the place where you will do most of your work.  Acts like a word-processor (you can type text and use many of the normal editing features like cut, paste, copy, find and replace).  To open a Code Window 1. Double-click a form or a control or press F7 2WRITING A CODE

3 Procedure/Events ComboBox Split Bar Object ComboBox Margin Indicator Bar  Four Elements of Code Window 3WRITING A CODE

4  Object Box ◦ Display the name of the selected object. ◦ Click the arrow to the right of the list box to display a list of all the objects associated with the form. ◦ If (General) is displayed in the Object box, the Procedure box lists any declarations and all of the general procedures that have been created for the form. ◦ If you are editing module code, the Procedure box lists all of the general procedures in the module. ◦ In either case, the procedure you select in the Procedure box is displayed in the Code window.  Margin Indicator Bar ◦ A gray area on the left side of the Code window where margin indicators are displayed. 4WRITING A CODE

5  Procedures/Events Box ◦ Lists all the events recognized by Visual Basic for a form or control displayed in the Object box. ◦ When you select an event, the event procedure associated with that event name is displayed in the Code Window. ◦ All the procedures in a module appear in a single, scrollable list sorted alphabetically by name. ◦ Selecting a procedure using the drop down combo boxes at the top of the Code window moves the cursor to the first line of the code in the procedure you select. 5WRITING A CODE

6  Split Bar ◦ Dragging this bar down splits the Code window into two horizontal panes; each of which scrolls separately. ◦ You can then view different parts of your code at the same time. ◦ The information that appears in the Object box and Procedures/Events box applies to the code in the pane that has the focus. ◦ Dragging the bar to the top or the bottom of the window or double-clicking the bar closes a pane.  You can drag selected text in a Code Window to: ◦ a different location in the current Code window ◦ another Code Window ◦ the immediate and Watch windows ◦ the Recycle Bin 6WRITING A CODE

7 The two boxes at the top of the Code Window are: ◦ Object List – lists all objects on the form by name. ◦ Procedure List – shows all possible event procedures for that control. Procedure list Object list Form Control – type to show or drop-down arrow. Load even procedure – shows after a program a written. 7WRITING A CODE

8 1.Click the Command button on the Toolbox. 2.Drag the mouse button inside the form window. The button is named Command1. Avoid writing lines of code that is wider than the displayed code window to make the code easier to read. You do not need to scroll left and right. 8WRITING A CODE

9 3.Click the CommandButton. 4.From the Properties window, change the Name to cmdBlack. 5.Change the Caption to Black. 6.Double-click the Black Command Button to view its code window. 7.Type in the procedure the Form1.Backcolor = vbBlack. 8.Press F5 button to run the program. Below is the Final result. Type cmdBlack Type Black 9WRITING A CODE

10 ◦ In the form file, all the event procedures, codes and variables are stored all together. By default, view all these codes together by just scrolling through it, if needed. This way of viewing the code is called Full module view. This is convenient for scanning through a lot of codes. The event procedures are listed one after the other. 10WRITING A CODE ◦ To change the window settings for Full Module View on default, do the following: 1.Click Tools in the Menu bar. 2.Click Options. 3.On the Editor Tab, uncheck Default to Full Module View. ◦ There are times when you prefer to view one procedure at a time. This way of viewing is called the Procedure view.

11 ◦ The two buttons at the bottom left corner of the code window are provided for you to switch on these two views. 11WRITING A CODE

12 ◦ One of the most useful form properties in any application is the Caption property. ◦ To put a Caption 1.Click a form. It will display the form’s property settings.  (If there is no form shown, use the drop-down list box at the top of the Properties Window) 2.Select the Caption property within the Properties Window. 3.Type the new Caption. 12WRITING A CODE

13 ◦ Programming is easier if you give the Code Window a bigger space. ◦ Clicking the Maximize button gives the Code Window all the spaces in the main window area, but it does not block out the Toolbox and Properties Window. It only blocks the Form Window. 13WRITING A CODE ◦ To maximize: 1.Click Maximize button. ◦ To minimize 1.Click Windows menu. 2.Click Cascade. The techniques make it possible to switch quickly between different form designers and form code which are very much useful in making large projects.

14 ◦ If you have a big project, bookmarks allow you to markdown some important variables or programs that you want to emphasize. 14WRITING A CODE COMMANDFUNCTION Toggle Bookmark CommandTo set the bookmark on the program line, provided that there is no bookmark yet on that line Next Bookmark Command Last Bookmark Command To go through different bookmarks within the program Clear All bookmarksTo remove all bookmarks Visual Basic shows a bookmark by displaying a blue square in the beginning of the program line.

15 ◦ To use Bookmark on a Code ◦ Quadratic (a,b,c), and variable declaration a=1. ◦ Print “Equation root is “ & _ 1.Place the cursor on the line you want to use the bookmark, and place the cursor on the variable declaration “a=1”. 2.Click Edit Menu from the Toolbar. 3.Select Bookmarks and then click Toggle Bookmark. 15WRITING A CODE

16 Other commands on the bookmark options: 16WRITING A CODE

17 ◦ To use Edit Toolbar 1.Display this toolbar by clicking the View menu. 2.Select Toolbars, then select Edit. 17WRITING A CODE Toggle Bookmark Next Bookmark Prev Bookmark Clear Bookmark

18 ◦ There are shortcuts in writing codes. The following are time-saving techniques. ◦ Print Command -One of the commonly used commands when making a program is the Print command. -Use the Print method only in the procedures as Form_Click, Form_Paint and Command1_Click.  To create a Print Statement 1.Type a question mark (?) before the variable you want to create. 2.Print the content of the variable “amount”, ? amount As you leave this line, the Visual Basic automatically translates it to: Print amount 18WRITING A CODE

19 ◦ The Finish-the-Word Feature (Auto List Member) -When typing the name of an object or methods using an object.member reference, Visual Basic shows you all the possible methods and property references on a pop-up list.  To use Finish-the-Word feature 1.Assume that Command1 is a command button. Type Command1.h in the Code Window. 2.Visual Basic responds by displaying the property or method beginning with H. 19WRITING A CODE

20  If Height happens to be the name you are looking for, simply press the spacebar button. Automatically, Visual Basic finishes the word by inserting the remaining characters.  If the names in the list are not the ones you are looking for, just continue typing. Arrow keys can also be used to select your desired name from the list. Press spacebar. The option Editor tab controls the feature Auto List Members. 20WRITING A CODE

21  Finding Argument Information -Another feature of Visual Basic is the way it automatically displays formal argument (parameter) information for functions and statements. It also performs any procedure that you define in a project. Example: The Mid Statement Mid ( ) As soon as you type the opening parenthesis, Visual Basic displays the argument list in complete form as shown below: 21WRITING A CODE Current Argument Optional Argument

22 This is called an argument list information in the Code window. Here are the following tips to remember:  The current argument – the one about to be typed is in Bold.  Optional arguments – (such as Length in this case) are in brackets.  Equal sign (=), if used, shows the default value.  The As clause shows what type of date is expected. If no type is given, Visual Basic assumes it as a Variant. Words and Characters should be string while Length should be a number. The argument should be clear. 22WRITING A CODE

23  Controlling Code Window Behavior Finish the word, argument list, and syntax checking are convenient Code Window automated features. ◦ To turn off the Code Window Automated features 1.Click the Tools menu. 2.Click on the Options. 3.Click the Editor Tab. 23WRITING A CODE Syntax Check feature checks each line for syntax error as soon as you leave the line. By default, this syntax checking is always on, checking all lines for errors. It is done after pressing Enter at the end of the line.

24 When writing a BASIC code, properly comment it. Place non-executable statements in your codes. Like most of the modern programming languages, Visual Basic has a comment symbol (‘). In a program, there are lines that you want the complier to ignore. These lines are sometimes called REM or remarks in other languages. Visual Basic supports that line comment syntax. If there is an apostrophe (‘) in the beginning of a line, everything on that line is ignored by the compiler. The comment symbol is an aid in understanding the code. ◦ To create a Comment 1.Use an apostrophe (‘). x=y ‘This is a comment; In this example, x=y is executed by Visual Basic, but the clause with apostrophe ‘This is a comment; isi gnored. 24WRITING A CODE

25 Debugging a program turns off a certain part of a program. It means many lines of a program are to be ignored by the compiler. Instead of putting apostrophe in all these lines one by one, Visual Basic allows you to easily comment out these lines by one command only. That is the Comment Block command. ◦ To use a Comment Block 1.Highlight all lines in the code window. 2.Click Comment Block on the Edit toolbar. 25WRITING A CODE Uncomment Block Comment Block

26 After clicking the Comment Block command, notice that apostrophe are placed in all the lines you highlighted. 26WRITING A CODE  To remove a Comment Block 1.Highlight the block. 2.Click the Uncomment Block command.

27 Information such as numbers, text, colors and pictures are needed in computer programming. These information should be stored temporarily. Control Properties such as size, appearance, colors and position on the form can be stored. Variables can hold information entered at runtime. Likewise, variables can store information which can change and vary during execution. These are the primary methods for moving information around VB project. They are simple tools to check almost any type of information.  Rules for naming variables:  Use no more than 40 characters.  Use only letters, numbers, and the underscore ( _ ) character.  The first character must be a letter. Do not use a reserved word, keywords, objects or properties as variable. Example: Form, Beep, Print, Sub…  Identify the information stored as its name.  Make your variable names descriptive. 27WRITING A CODE

28  Variables to Store Input Use the InputBox function to display a dialog box on the screen. Store the text in a variable rather than in a property. It is a special function that shows a dialog box on the screen and prompts the user to input. It is used to prompt the user anytime for information. 28WRITING A CODE

29  Sample 1. Prepare the Form. A form with buttons and a label for displaying output. 2.Double-click the Inputbox CommandButton. The cmdInput_Click event procedure is shown in the Case Window. 3.Type the program statements to declare two variables. 29WRITING A CODE 4.Click the Start button on the toolbar to run the program. 5.Click the InputBox button and an Input dialog box appears on the screen. 6.Type the school name and click OK. 7.Click the Quit button to stop the program. 8.Save the form and project.

30  Variable for Output For displaying the contents of a variables, the useful dialog box function is the MsgBox function. MsgBox function takes one or more arguments as input, and the output of the function call can be assigned to a variable. It uses text strings to display output in a dialog box. It supports a number of optional arguments. Syntax: ButtonClicked = MsgBox (Message, NumberofButtons, Title) 30WRITING A CODE Text to be displayed Button style number Text displayed in the message box title bar

31  To display a message 1. Use the Code Window for Input Check project. Double-click the InputBox button. 2. Use the line Label1.Caption = SchoolName 3.Press Del to delete the line. 4.Type the following line as a replacement. MsgBox “Input Results” Code: Private Sub cmdInput_Click() Dim Prompt, SchoolName Prompt = "Please enter the name of the school." SchoolName = InputBox$( Prompt) MsgBox “Input Results” End Sub 5.Click the Start button on the toolbar. 6.Click the InputBox button, type your name and then OK. 7.Click OK to close the message box. Then click Quit to close the program. 31WRITING A CODE

32  Variable Types The types of variables are Integer, Long, Boolean and String. Single type is a number that has a decimal point, a floating-point number. Example: 4.00-2.44.1625 It can be written as assignment statement. VariableName = NewValue  Declaring and Using Variables Variables are used in programming. Proper variable declaration makes programming easier, minimize the possibility of program errors, and makes later program modification easier. A variable is a named location for storing data. The name of a variable such as (I,x, amount, myname, mydata, etch…) as well as its properties never change, but the data it stores can always be changed. 32WRITING A CODE

33  The Dim Statement for making reservation of variables If you type the variable name after the Dim statement then you explicitly declare a variable before using it. This reserves space for a variable when the program runs and it allows VB to know what type of data to be shown. Example: Dim Surname If the variable holds a small number without any decimal places (an integer), you can declare the variable as an integer and save some memory space. The Dim statement is used to declare a couple of variables. Dim lString, p Dim, in its simplest usage, declares one or more variables separated by commas if there are more than one. However, Dim can also employ a much richer and more complex syntax. Other statements for declaring variables are Publlic, Private, Static and Redim that define how and where the variable can be used. 33WRITING A CODE

34  Implicit Variables and Variant Type Visual Basic reserves space for a variable by default as variant. The variant is extremely flexible. You are free to assign information to a variable after declaring it in your code. Example: Surname = “Reyes” The surname variable can be used in place of the name “Reyes” in your code. The assignment statement: Label1.Caption = Surname Other programming languages, such as C and Pascal, require a programmer to declare a variable first before the program can be used. Visual Basic programming does not do so. VB programmer can immediately use the program. Visual Basic automatically adjusts. 34WRITING A CODE

35  To declare variables without Dim statement The process of declaring without Dim is called Implicit Declaration. This declaration does not help you to organize and list your variables in advance. Implicit variables are variables which are not declared. Find which are implicit variables in the program below. Private Sub Command1_Click () answers = Array (“Hi”,”Hello”,”How are you?”,“Have a nice day!”) Randomize n = Int (4 * Rnd) Text1.Text = answers (n) End Sub 35WRITING A CODE

36  To declare variables without Dim statement In the program, there are 2 variables: n and answers. Any name that is not a keyword will definitely be a variable. The words answers and n are definitely variables because they are neither keywords, object names or procedures. Therefore, it is a variable, Visual Basic also gives it a default type, which is called a Variant. Variant is a type of variable which any type of data can be placed as numeric, text or even arrays. Technically, Text1 and Command1 are identifiers. Identifiers are user-created names. Randomize, Int, Rnd, and Text are keywords. There is, however, a setback on this feature. What if we have misspelled a word? Visual Basic can misquote a misspelled word as a variable. It will be very hard to find a misspelled word especially if you have a very big code. 36WRITING A CODE

37  To declare variables without Dim statement 1.Create the Form. 2.Double-click the Show CommandButton. 3.Encode the program statement: Private Sub Command1_Click() Dim Surname Surname = "Good" Label1.Caption = Surname Surname = 99 Label2.Caption = Surname End Sub 4.Click the Start button on the toolbar to run the program. 5.Click the Show button. 6.Click the Quit button to stop the program. 37WRITING A CODE

38  To declare variables without Dim statement 38 WRITING A CODE

39  Option Explicit and Declarations The Option Explicit in the VB program offers a flexible option if you really want to make sure that all you variables are declared before it can be used. When this statement is used, all variables must be declared with statements such as Dim, Public and Private. This kind of option is effective if you have a very big and long code. Type Option Explicit without any argument or optional syntax. It cannot be placed inside a procedure. Instead, it must be placed inside the Declarations section of a form or module. The Visual Basic generates an error message whenever it finds a variable that has not been explicitly declared in the Code. 39WRITING A CODE

40  Option Explicit and Declarations  To go to the Declarations section using the Code window 1.Open the Code window by clicking any object or command in the form. 2.In the Object ListBox, click the drop-down list at the top left portion, then select General. 3.In the Procedure ListBox, click the drop-down list at the top right portion, then select Declarations. The cursor is already placed at the beginning of the procedure. Start typing Option Explicit statement. Once Option Explicit is added to the form code, all variables must be declared before it can be used. 40WRITING A CODE

41  Option Explicit and Declarations  To show Option Explicit in the General Declarations 1.Click Tools, then Options. 2.Choose Editor tab. 3.Put a check in the box next to Require Variable Declaration. 41WRITING A CODE

42  Fixed-Length Strings Variable length strings are mostly used in the programs. These can have any amount of text until 2 billion characters. Implicit and explicit declarations create variable-length strings or fixed length strings. A fixed-length string has the same size even if the expression is shorter or longer. It fills spaces if there are remaining spaces or truncates if the expression is too long. It can only be declared using an explicit expression. Dim varname As String * strlength Shows that the string final parameter, tells the maximum Has a fixed length number of characters that the variable can contain Example:Dim sName As String * 25 Sname = “this word is too short for the string Variable? 42WRITING A CODE

43  Using Specific Types in Declarations The type of variables that you have declared are the types of information you want your variable to store. It can be of the following: Integer, Long, Single, Double, Boolean, Currency, Date, String. You can declare one as variant although this type is default. There are many advantages in using more specific types.  Specific types are more efficient. If you have already assigned a specific type, it will reduce the memory required for your program. A variant uses two extra bytes in memory to indicate what type of data will be stored.  There may be instances when you need to be precise about what kind of data you are about to store. In file operations, using a variant variable can cause some errors if you are not extremely careful.  It is a good programming practice to always think of the kind of data you intend to store in your variable. 43WRITING A CODE

44  To declare a type, use Dim Statement: Dim varname As type Dim n As Integer, s as String, aString as String Do not mix variable names and type because doing so will result to errors which are hard to debug. In the following declaration, which variable is Integer and which is Long? Dim a, b, c, n As Integer, total As Long Integer type means short signed numbers can be used Long type means long signed numbers can be used Single type means short floating points or numbers with fractions can be used Double type means long floating points or number with fractions can be used 44WRITING A CODE

45  Form Variables Form variables are strictly used in one procedure only. If the procedure is done, the value of the variable is also lost; and these values are not shared with other procedures. Just like in using Option Explicit, the variables to be used in all procedures must be declared in the Declaration section of the Code window. 45WRITING A CODE To create a variable that retains a value between calls to the same procedure, but is not shared with other procedures, use the Static keyword in place of Dim. Static n As Integer ‘n retains value between calls.

46  Public and Private Variables  Public Variables To create variables that are available everywhere is to declare a global or public, variable in a standard module. Type the keyword Public followed by a variable name. Example:Public Computing Product After declaring the variable, you can read, change or display in any procedure. By default, Public variables are declared as variant types. You can specify a fundamental type name by using the As keyword. Example:Public Firstname As String 46WRITING A CODE

47  Public and Private Variables  Private Variables To keep a variable local, use the Dim or Private keywords. These keywords define the variable within the scope of the current procedure or form. The variable to every procedure if it is defined in the General Declaration section. This type is called form-level or module-level variable. Local variable declared variable inside a procedure can be used only within a procedure. 47WRITING A CODE INFO :If your code relies on a public variable, it is difficult to maintain and debug.

48  Static Variables To create variables that are retains its value, declare the variable using the Static keywords. This keyword tells the Visual Basic that the variables can be referenced only within the procedure. It is stored and can be used when needed again. Static nAddressNumber As Integer Example:Static Sub Test() Dim n As Integer Debug.Print “Value of n before assignment statement = “&n n = 4321 Debug.Print “Value of n after assignment statement = “&n End Sub n is static variable. If you call the Test function, the output would be 0 and 4321 for both before and after values. 48WRITING A CODE

49  Static Variables When declaring variables, you can You can also declare more also use Private and Public in place specific with types such as: of Dim keyword. Dim a, b, c Dim w As Integer, l As Integer Public d, e, f Public x As Double, y As Single Private g, h, I Private temp as String The Dim and Private declarations are the same when you put them in the program. Likewise, those variables that are declared in the Declaration sections and the Public keywords are the same. Private keyword means that the variable declared using it can be used only inside a procedure. Public keyword means that a variable declared using it can be used and shared with other procedures within a program. 49WRITING A CODE

50  Defining New Procedures General-purpose procedures are built in Visual basic statements and functions which are called by name. These procedures can receive arguments and do special tasks. They save typing time, reduce errors, make programs shorter and easier to handle. They make event procedures easier to read.  Types of Procedures Function procedures are called by name from event procedures. They can receive arguments and return a value in the function name. They are used for calculations and exactly like applying a built-in function as Str and Int. A Function procedure returns a value, and when a function is called, parenthesis around the argument list is needed. It has a return type which may be implicitly declared or a variable type. 50WRITING A CODE

51  Defining New Procedures As a Variant Function getRnd(n) Randomize Get Rnd = 1 + Int (n*Rnd) End Function As Long Function getRnd(n) As Long Randomize Get Rnd = 1 + Int (n*Rnd) End Function 51WRITING A CODE

52  Writing Function Procedures Function procedure is a collection of statements located between a Function statement and an End Function statement in a standard module. Syntax of a function: Function FunctionName ([arguments]) {As type] function statements End Function  Function Name is the name in the standard module.  Argument is a list of optional arguments to be used in the function.  As Type specifies the function return type (the default is variant).  Function statement is a block of statements that accomplishes the work of the function. 52WRITING A CODE INFO :Function has a type. Brackets ([]) are used to enclose optional syntax items.

53  Writing Function Procedures Functions always return a value of the calling procedure in the function Name. The last statement is often an assignment statement that places the final calculation of the function. Example: Function Total_Earnings Salary = Basic + Allowance Commission = Sales * 0.15 Total Earnings = Salary + Commission End Function 53WRITING A CODE

54  To call a Function Procedure lb1Earinings.Caption = Total Earnings(12) This computes Total Earnings for 12 months and assign the output to the Caption property of the lb1Earnings object. General procedures include both Function and Sub procedures. The execution of code begins when an event procedure is called Event procedures can call general procedures. Subprocedures are called by name from event procedures or other procedures. They receive arguments and can be used to perform tasks in the procedure and return values. They are used to receive or process input, display, output or set properties. 54WRITING A CODE

55  Syntax of a subprocedure Sub ProcedureName ( [ argument ] ) procedure statements End Sub Sub Procedures:  do not return a value associated with its name  use to find input from the user  display or print data  manipulate several properties associated with a condition  used to process and return different variables. ProcedureName is the name of the subprocedure you are making. Argument is a list of optional arguments. Procedure statement is a block of statement that accomplishes the work of the procedure. 55WRITING A CODE INFO :By default, Sub Procedures declared in a standard module are public.

56  To add friendnames to a list box on a form at runtime Sub AddFriendName to Listbox (people$) If people $<> “ “ Then Form1.List1.AddItem people $ Msg$ = people$& “added to list box.” Else Msg$ = “Name not given.” End If MsgBox (Msg$)., “Add name” End Sub 56WRITING A CODE

57  To call a Sub Procedure Specify the name of the procedure and list the arguments Example: Add NameTo Listbox “Jose” Use a variable (call it by reference) Example: Add NameToList box New Name Call the procedure may times to save space Add NameToList Box “Jose” Add NameToList Box “Hermie” Do ‘then let user add names NewName$ = InputBox(“Enter a listboxnames”, “Add Name”) Add NameTo_ListBox NewNames) Loop Until NewName$ = “ “ 57WRITING A CODE

58 The Subprocedure declaration consists of Sub and End statements. Sub statement specifies the name of the procedure. Another method to declare procedure is to use Add Procedure in the Tools Menu. This does not automate entering arguments or return-value type for functions. Remember not to place parenthesis around a Subprocedure argument list during a call. 58WRITING A CODE Sub Showlove (n, msg) s = “Error” & n & “:” & msg MsgBox s End Sub Procedure Argument List Default Type

59  To create a Message Box 1.Go to Code Editor window. Press F7. 2.Choose General and Declaration on the right combobox. 3. Type the following: Sub Close_end() MsgBox “Goodbye!!!!”,,”Message” End End Sub 4. Create a commandbutton. Name it As Close. Then, double-click the Close commandbutton. Type the Following code: Private Sub cmdclose_Click() Close_end End sub 5. Press F5 to run the program. 59WRITING A CODE


Download ppt "By : Jonthy L. Cabatuan 1WRITING A CODE.  The integral part of a programming language is the programming itself.  Code Window  is a turbo-charged text."

Similar presentations


Ads by Google