590 likes | 726 Views
DCIT22_Computer Programming II. By : Jonthy L. Cabatuan. Writing A Code. 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.
E N D
DCIT22_Computer Programming II By : Jonthy L. Cabatuan WRITING A CODE
Writing A Code • 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 • Double-click a form or a control or press F7 WRITING A CODE
Writing A Code Procedure/Events ComboBox Object ComboBox Split Bar Margin Indicator Bar • Four Elements of Code Window WRITING A CODE
Code Window Elements • 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. WRITING A CODE
Code Window Elements • 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. WRITING A CODE
Code Window Elements • 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 WRITING A CODE
Writing a Code and Setting a Caption 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. WRITING A CODE
To write a Code • Click the Command button on the Toolbox. • 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. WRITING A CODE
To write a Code • Click the CommandButton. • From the Properties window, change the Name to cmdBlack. • Change the Caption to Black. • Double-click the Black Command Button to view its code window. • Type in the procedure the Form1.Backcolor = vbBlack. • Press F5 button to run the program. Below is the Final result. Type cmdBlack Type Black WRITING A CODE
Viewing One Procedure at a Time • 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. • To change the window settings for Full Module View on default, do the following: • Click Tools in the Menu bar. • Click Options. • 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. WRITING A CODE
Viewing One Procedure at a Time • The two buttons at the bottom left corner of the code window are provided for you to switch on these two views. WRITING A CODE
Setting a Caption • One of the most useful form properties in any application is the Caption property. • To put a Caption • 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) • Select the Caption property within the Properties Window. • Type the new Caption. WRITING A CODE
Sizing and Tiling the Window • 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. • To maximize: • Click Maximize button. • To minimize • Click Windows menu. • 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. WRITING A CODE
Using Bookmarks • If you have a big project, bookmarks allow you to markdown some important variables or programs that you want to emphasize. WRITING A CODE
Using Bookmarks • To use Bookmark on a Code • Quadratic (a,b,c), and variable declaration a=1. • Print “Equation root is “ & _ • Place the cursor on the line you want to use the bookmark, and place the cursor on the variable declaration “a=1”. • Click Edit Menu from the Toolbar. • Select Bookmarks and then click Toggle Bookmark. WRITING A CODE
Using Bookmarks Other commands on the bookmark options: WRITING A CODE
Using Bookmarks • To use Edit Toolbar • Display this toolbar by clicking the View menu. • Select Toolbars, then select Edit. Toggle Bookmark Next Bookmark Prev Bookmark Clear Bookmark WRITING A CODE
Features in Entering A Code • 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 • Type a question mark (?) before the variable you want to create. • Print the content of the variable “amount”, ? amount As you leave this line, the Visual Basic automatically translates it to: Print amount WRITING A CODE
Features in Entering A Code • 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 • Assume that Command1 is a command button. Type Command1.h in the Code Window. • Visual Basic responds by displaying the property or method beginning with H. WRITING A CODE
Features in Entering A Code • 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. WRITING A CODE
Features in Entering A Code • 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: Optional Argument Current Argument WRITING A CODE
Features in Entering A Code 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. WRITING A CODE
Features in Entering A Code • 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 • Click the Tools menu. • Click on the Options. • Click the Editor Tab. • 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. WRITING A CODE
COMMENTS & COMMENT BLOCK COMMAND 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 • 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; isignored. WRITING A CODE
COMMENTS & COMMENT BLOCK COMMAND 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 • Highlight all lines in the code window. • Click Comment Block on the Edit toolbar. Uncomment Block Comment Block WRITING A CODE
COMMENTS & COMMENT BLOCK COMMAND After clicking the Comment Block command, notice that apostrophe are placed in all the lines you highlighted. • To remove a Comment Block • Highlight the block. • Click the Uncomment Block • command. WRITING A CODE
VARIABLES 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. WRITING A CODE
VARIABLES • 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. WRITING A CODE
VARIABLES • Sample • Prepare the Form. A form with buttons and a label for displaying output. • Double-click the InputboxCommandButton. The cmdInput_Clickevent procedure is shown in the Case Window. • Type the program statements to declare two variables. • Click the Start button on the toolbar to run the program. • Click the InputBox button and an Input dialog box appears on the screen. • Type the school name and click OK. • Click the Quit button to stop the program. • Save the form and project. WRITING A CODE
VARIABLES • Variable for Output For displaying the contents of a variables, the useful dialog box function is the MsgBoxfunction. 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) Text to be displayed Button style number Text displayed in the message box title bar WRITING A CODE
VARIABLES • To display a message • Use the Code Window for Input Check project. Double-click the InputBoxbutton. • Use the line Label1.Caption = SchoolName • Press Del to delete the line. • 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 • Click the Start button on the toolbar. • Click the InputBox button, type your name and then OK. • Click OK to close the message box. Then click Quit to close the program. WRITING A CODE
VARIABLES • 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.4 4.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. WRITING A CODE
VARIABLES • 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. WRITING A CODE
VARIABLES • 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. WRITING A CODE
VARIABLES • 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 WRITING A CODE
VARIABLES • 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, Text1and Command1are 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. WRITING A CODE
VARIABLES • To declare variables without Dim statement • Create the Form. • Double-click the Show CommandButton. • Encode the program statement: Private Sub Command1_Click() Dim Surname Surname = "Good" Label1.Caption = Surname Surname = 99 Label2.Caption = Surname End Sub • Click the Start button on the toolbar to run the program. • Click the Show button. • Click the Quit button to stop the program. WRITING A CODE
VARIABLES • To declare variables without Dim statement WRITING A CODE
VARIABLES • 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. WRITING A CODE
VARIABLES • Option Explicit and Declarations • To go to the Declarations section using the Code window • Open the Code window by clicking any object or command in the form. • In the Object ListBox, click the drop-down list at the top left portion, then select General. • 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. WRITING A CODE
VARIABLES • Option Explicit and Declarations • To show Option Explicit in the General Declarations • Click Tools, then Options. • Choose Editor tab. • Put a check in the box next to Require Variable Declaration. WRITING A CODE
VARIABLES • 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? WRITING A CODE
VARIABLES • 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. WRITING A CODE
VARIABLES • To declare a type, use Dim Statement: Dim varnameAs 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 WRITING A CODE
VARIABLES • 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. 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. WRITING A CODE
VARIABLES • 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 WRITING A CODE
VARIABLES • 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. INFO : If your code relies on a public variable, it is difficult to maintain and debug. WRITING A CODE
VARIABLES • 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. WRITING A CODE
VARIABLES • 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. WRITING A CODE
VARIABLES • 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 Strand 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. WRITING A CODE