Programming Basic |
---|
Hardware | is the equipment or machinery associated with a
computer.
Software
| refers to the data and instructions used to generate information.
| |
---|
Input | Data
Storage
| |
Process
| a running software
| Processor
| CPU (Central Processing Unit)
| Computer Program
| Software
| Output
| Information is output in a useable form
| |
---|
System software | Windows is an example of system software.
Application software
| Word is an example of application software.
| |
---|
Programming- Programmers write programs
Testing and debugging
| |
---|
Accept data via input device
Store Data in Memory
| Variables
| Perform Arithmetic operations (add, subtract, multiply, divide) on data
| Compare data to other data
| determine if one value is less than, greater than, or equal to another value
| Output Results via output device
| |
---|
Machine Language | the only language the computer really understands. No one really write in machine language. Instead an assembler, compiler, or interpreter converts the instructions written by the programmer, (the source code) into machine language.
Low-Level Language
| closest to machine language
| Assembly Language
| High-Level Languages
| closer to English
| Cobol, C, C++, Java, Fortran, Perl, RPG, Visual Basic,
| Fourth-Generation Language
| Intended for programmer as well as non-programmer use
| SQL, FOCUS
| |
---|
Source Code | instructions written in a computer language
Assembler
| Assembly languages are assembled.
| Compiler
| Checks all instructions in a high-level program for syntax errors, if any error is found a list of detected errors is produced. If no errors are found the entire program is translated into machine code and stored in machine language ready for execution.
| Interpreter
| Checks instructions in a high-level program for syntax errors one line at a time. If no error is found the instruction is translated into machine code then executed and the interpreter moves on to the next line in sequence.
| |
---|
What is Visual Basic? |
---|
high-level Programming Language
Event oriented
| As opposed to procedure oriented. In a procedural language there is always a beginning, middle, and an end.
| High-visual
| Uses a GUI (Graphical User Interface)
Interpreted in development stage
| Can be compiled
| The runtime file - msvbvm60.dll usually found in the System
directory is needed to run a Visual Basic application
without the Visual Basic program.
| |
---|
1991 | 1.0
1992
| 2.0
| Faster
| 1993
| 3.0
| Simple way to control databases
| 1995
| 4.0
| Supports 32-bit processing. It generates 32-bit applications for Windows 95 or NT. Began providing developers with some object-oriented capabilities.
| 1997
| 5.0
| New interface. Programmers can create their own controls.
| 1998
| 6.0
| Includes new data access and Web development features.
| 2002
| .NET
| Major changes (among other things) enhances Internet Application
| |
---|
Learning Edition | Allow beginning Visual Basic Programmers to easily create powerful applications for the Windows platform. It includes all intrinsic controls, plus grid, tab, and data-bound controls. Documentation includes Learn VB Now (a multimedia CD-ROM title), plus Microsoft Developer Network CDs containing full on-line documentation.
Professional Edition
| Designed for professional programmers. Includes all the features of the leaning edition plus additional ActiveX controls, the Internet Information Server Application Designer, Integrated Data Tools and Data Environment to support high-speed database access, and the Dynamic HTML Page Designer. Documentation includes the Visual Studio Professional Features book.
| Enterprise Edition
| Intended for development and support of robust distributed applications in a team setting. Includes all the features of the Professional edition plus Back Office tools such as SQL Server, Microsoft Transaction Server, Internet Information Server, Visual SourceSafe, SNA Server and more.
| |
---|
Working Edition | Like the Learning Edition but may not compile to an .EXE file and no online Documentation. Comes with textbooks.
VBA/Visual Basic for Application What is Visual Basic
| Included with Microsoft Office applications to provide programming-development capability from within them.
| |
---|
3 kinds of Errors |
---|
Programming Process |
---|
State the output requirements | What are you trying to do?
Identify the available input
| What are you given to work with?
| Determine necessary processing
| What do you have to do with or to the available input to produce the desired output?
| |
---|
Structure Charts | Flowchart
| Pictorial representation of a program solution
| Pseudocode
| Solution to programming task that is language independent
| Walkthrough
| | |
---|
Compile Program | Syntax Errors – A violation of the rules of the language.
Example: Pint "Hello World " (Print is misspelled) Test Program
| Logic Errors – when a program does exactly what it is told to do but not what the programmer intended it to do.
| Example: GrossPay = PayRate / HoursWorked |
---|
Constants and Variables |
---|
Numeric constants |
Nonnumeric constants
|
Anything enclosed in quotation marks is considered a Nonnumeric constant, also called string constants or alphanumeric constants or literals
| Nonnumeric constants SHOULD NOT be used in calculations For example - "Hello World", "5", "Five", "", (Quotes with nothing, not even a space between them are called a zero-length string or empty string.) |
---|
Unique within scope
<= 255 characters (other languages may have different length restrictions)
| Begin with a letter
| No embedded spaces or many special characters (. , “ - $ # * and others). The underscore _ is a valid character.
| Cannot be a reserved word
| Use upper and lower case with purpose.
| Once a variable is declared you do not have to be concerned with upper/lower case. The editor recognizes words that are the same except for case and makes them all the same for you. (use of upper and lower case differ between languages) It is always good programming practice to use names that are descriptive or mnemonic.
| |
---|
Invalid, Valid Variable Name Exercise |
---|
Variable Name | Valid? | Invalid? | Good Variables Name? | If not why?
GPA
| YES
|
|
|
| Count#1
|
|
|
|
| $grosspay
|
|
|
|
| GradePointAverage
|
|
|
|
| Attempted.Hours
|
|
|
|
| Attempted-Hours
|
|
|
|
| Interest Rate
|
|
|
|
| A2
|
|
|
|
| 2A
|
|
|
|
| Print
|
|
|
|
| Printitout
|
|
|
|
| MONEYAFTERALLTAXES
|
|
|
|
| |
---|
Unique within scope
<= 255 characters (other languages may have different length restrictions)
| Begin with a letter
| No embedded spaces or many special characters (. , “ - $ # * and others). The underscore _ is a valid character.
| Cannot be a reserved word
| Use upper and lower case with purpose. Once a variable is declared you do not have to be concerned with upper/lower case. The editor recognizes words that are the same except for case and makes them all the same for you. (use of upper and lower case differ between languages)
| It is always good programming practice to use names that are descriptive or mnemonic.
| |
---|
Data Types |
---|
Nonnumeric data type | (called String, text, alphanumeric, or character data in different languages
) can be used to store any kind of data.
Numeric data types
| are used to store numbers.
| |
---|
String | String variables are a nonnumeric data type that can be used to store text values up to 2 billion characters long. The maximum length will differ on individual machines because of available memory, overhead, and other programs.
Any characters may be stored in a string variable. Integer
| Integer data type can be used to store a whole number between -32,768 to 32,767
| Long
| Integer data type can be used to store a whole number between -2,147,483,648 to 2,147,483,647
| Note: If you know that a variable will always store whole numbers (such as 12) rather than numbers with a fractional amount (such as 3.57), declare it as an Integer or Long type. Operations are faster with integers, and these types consume less memory than other data types. Single
| Is used to store single-precision floating-point numbers. In other words they are used to store numbers with fractions.
| Double
| Is used to store double-precision floating-point numbers. That is numbers that are very large, very small, or have many decimal positions.
| Boolean
| Variables are used as a flag or switch. The value of a Boolean variable is either True or False. Boolean variables are used to indicate the absence or presence of a certain condition. The properties Default, Cancel, Visible, and Enabled are all Boolean properties.
| Date
| The date data type can store a date anywhere from Jan 1, 100 to Dec 31, 9999. The date is stored as a number of days from 12/30/1899. Negative numbers reflect dates prior to 12/30/1899.
| Time is stored in the decimal portion of a Date type variable. |
---|
Internal Data Representation |
---|
0 1 1 0 0 0 0 1 |
---|
9 * 100 = 9 (any number raised to the power of zero equal 1) + 8 * 101 = 80 (any number raised to the power of one equals itself) + 7 * 102 = 700 9 + 80 + 700 = 789 |
---|
0 1 1 0 0 0 0 1 _ _ _ _ _ _ _ _ 27 26 25 24 23 22 21 20 |
---|
1 * 20 = 1 +0 * 21 = 0 +0 * 22 = 0 +0 * 23 = 0 +0 * 24 = 0 +1 * 25 = 32 +1 * 26 = 64 +0 * 27 = 0 1 + 32 + 64 = 97 |
---|
0 1 1 0 0 0 0 1 _ _ _ _ _ _ _ _ 27 26 25 24 23 22 21 20 |
---|
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 215 214 213 212 211 210 29 28 27 26 25 24 23 22 21 20 |
---|
Declaring Variables in Visual Basic |
---|
Dim intNumber as integer Dim sngInterestRate as single |
---|
intNumber | The prefix int would signify an integer variable, use lng for Long
sngHours
| The prefix sng would signify an single variable, use dbl for Double
| strName
| The prefix str would signify a string variable
| blnYearEnd
| The prefix bln would signify a Boolean variable
| dtmBDay
| The prefix dtm would signify a date/time variable
| |
---|
Dim intnumber as integer, sngamount as single, lngBigNumber as long |
---|
Dim intnumber as integer Dim sngamount as single Dim lngBigNumber as long |
---|
Variable Declaration Exercise |
---|
Information | Declaration
1.
| Age
| Dim intAge as Integer
| 2.
| Address
| | 3.
| FICA tax withheld
| | 4.
| GPA
| | 5.
| Marital status
| | 6.
| End of month flag
| | 7.
| Social Security number
| | 8.
| Date account opened
| | 9.
| Telephone number
| | 10.
| Beginning of shift
| | 11.
| Account closed indicator
| | 12.
| Interest rate
| | 13.
| Number in stock
| | |
---|
Identifying Variables, Constants |
---|
Numeric | variable or constant
String
| variable or constant
| Undetermined
| | |
---|
Data | Numeric? | Nonnumeric? | Constant? | Variable? | ????
5.5
| yes
| No
| yes
| no
| strName
|
|
|
|
| "5.5"
|
|
|
|
| -250
|
|
|
|
| intScore
|
|
|
|
| Five
|
|
|
|
| "Parkland College"
|
|
|
|
| sngRate
|
|
|
|
| .0875
|
|
|
|
| 0
|
|
|
|
| "Invalid Date Vreenter"
|
|
|
|
| ""
|
|
|
|
| |
---|
Assignment Statements |
---|
Let variable/property = Variable
Let variable/property = Property
| Let variable/property = Constant
| Let variable/property = Expression
| |
---|
Let frmMain.Caption = strFileName
Let lblOutput.Caption = txtInput.Text
| Let txtInput.FontSize = 24
| Let dblGrossPay = sngPayRate * sngHours
| |
---|
frmMain.Caption = strFileName lblOutput.Caption = txtInput.Text |
---|
lblOutput.caption = "" txtInput.text = "" |
---|
intCount = 0 |
---|
strName = "Clinton Lien" |
---|
blnSalaried = True |
---|
dtmDateHired = #01/31/98# |
---|
dtmEndTime = "9:50" |
---|
Internal Documentation |
---|
‘Author: Kari Couch ‘Lab 1: The purpose of this lab is to declare variables of different types, assign them values, and display them in a picture box with appropriate labels. |
---|
Visual Basic Terms |
---|
Object | An object consists of code and data that work together as a unit. Most of the objects we will be working with are controls.
Control
| Object attached to a form
| Form
| Container or windows for other forms and controls
| Property
| Attribute or characteristic that control an object’s appearance or behavior
| Setting
| Current value of a property. Initial value established in property window but can be altered using code.
| Event Driven
| A program is written to respond to actions taken by the user. The user is somewhat in control of the order of operations.
| Event
| Action that is recognized by an object
| ♦ Examples
Event Procedure
|
Code written to tell the program how to respond when an event occurs.
Events are associated with objects.
| ♦ objectname_event()♦ Example:
Code or Instructions
| Tell the program what to do and are
entered in the Code Window
| ♦ Print "This is an output message" Assignment Statement
|
| ♦ objectname.property = settingExample
Method
| A procedure that is connected to an object. Action an object is capable of performing
|
♦ Format: object.methodExample:
|
---|
Event, Control, Property |
---|
Click
Keypress
| Gotfocus
| Lostfocus
| Dblclick
| Change
| Keydown
| Dragdrop
| |
---|
Command Button | V used by the user to initiate an action
Label
| Used to display text the user cannot change
| Text Box
| Used to accept text input from the user.
| Option Button
| Used for user input
| Check Box
| Used for user input
| Combo Box
| | Directory List Box
| | Drive List Box
| | File list Box
| | Frame
| | List Box
| | Scroll Bar
| | |
---|
Caption | Controls what appears in the title bar of Form and what is displayed on Command Buttons and Labels (An Access Key can be created for a control by inserting an & before a letter in the Caption. An Access key allows the user to select an object using the Alt key in combination with a letter.) The Caption is not related to the Name property.
Name
| The name used to refer to the object while writing code. Similar to a variable name, the Name must begin with a letter and be no more than 40 characters long.
| Objects are given default names when created. You should rename objects using the standard prefixes (in lowercase) for the control type followed a word that describes its function (beginning with an uppercase letter).
Cancel
| If the setting for the cancel property is True pressing the esc key generates the click event for this button.
| Default
| If the setting for the default property is True pressing the enter key will generate the click event for this button unless another command button has focus.
| Focus
| Object that is active or ready for input is said to “have focus”.
| Text
| The value displayed or typed in a textbox is stored in the Text property of the textbox.
| TabIndex
| Determines the order controls receive focus when the user uses the Tab key.
| If the value of TabIndex = 0 this object will have focus when Form is loaded. Object with TabIndex = 1 will have Focus after pressing the Tab key once. TabIndex is automatically set to 0 for first control placed on form, next = 1 and so forth. You can change the TabIndex in the Properties window. |
---|
Designing the User Interface |
---|
Design Time, Run Time, and Break Mode |
---|
Mode | Description
Design time
| Most of the work of creating an application is done at design time. You can design forms, draw controls, write code, and use the Properties window to set or view property settings.
| From the Run menu, choose Start, or click the Run button to switch to run time. Run time
|
When an application takes control, you interact with the application the
same way a user would. You can view code, but you cannot change it.
Sometimes it may appear that you machine is "hung" because it does
respond to any keyboard input in the code window.
This is usually because you are in Run Mode.
| From the Run menu, choose End, or click the End button to switch back to design time. Break mode
| From the Run menu, choose Break, click the Break button, or press
CTRL+BREAK to switch to break mode.
| Execution is suspended while running the application. You can view and edit code (choose Code from the View menu, or press F7), examine or modify data, restart the application, end execution, or continue execution from the same point. |
---|
Mode | Toolbar buttons available
Design time
| Start
| Run time
| Break, End
| Break
|
Continue, End (in break mode, the Start button becomes the Continue button)
| |
---|
Concatenation - & |
---|
lblOutput.Caption = "This is a very long message which " _ & Chr(13) & Chr(10) & "will need more than one line to " _ & vbCrLf & "display" _ & vbNewLine _ & vbNewLine & "Please respond” |
---|
Dim strName As String strName = "Joe Smith" lblOutput.Caption = "This is a very long message which " _ & vbNewLine & "will need more than one line to " _ & vbNewLine & "display" _ & vbNewLine _ & vbNewLine & "Please respond [K1] " & strName |
---|
Concatenation exercise |
---|
the variable strFName contains the string | Joe
the variable strMiddleIntial contains the string
| L
| the variable strLName contains the string
| Smith
| |
---|
Expression | Answer
1. strFName & strMiddleInitial & strLName
| JoeLSmith
| 2. "strFName" & "strMiddleInitial" & "strLName"
| | 3. strFName & ""strMiddleInitial & "." & strLName
| | 4. strFName & " " & strMiddleInitial & ". strLName"
| | 5. strFName & " " & strMiddleInitial & ". " & strLName
| | |
---|
Functions |
---|
strUpper = UCase("abc") |
---|
strName = UCase(txtName.text) |
---|
Creating an Executable File |
---|
Choose Make xxxxx.exe from the file menu.
![]()
| |
---|---|
And then using the drop down Save In list box travel to the location you wish to save the executable file at
![]() | |
You can change the name of the file at this point.
Choose OK.
| |
Math Operators |
---|
Let variable/property = Variable
Let variable/property = Property value
| Let variable/property = Constant
| Let variable/property = Expression
| |
---|
Arithmetic | Used to do calculations
Concatenation
| Used to put strings together
| Relational
| Used in comparisons
| Logical
| Also used in comparisons
| |
---|
Exponentiation | ^
Negation
| -
| Multiplication
| *
| Division
| /
| Integer Division
| \
| Modulus Division
| Mod
| Addition
| +
| Subtraction
| -
| |
---|
Regular division | 11 / 2 = 5.5 | returns a floating point (with decimals) answer
Integer division
| 11 \ 2 = 5
| returns a whole number, discarding the remainder
| Modulus division
| 11 Mod 2 = 1
| returns only the remainder
| |
---|
sngRadius^2
-intyardage
| sngAmount * sngSalesTaxRate
| intTotal / intCount
| sngAmount + sngSalesTax
| sngAmount - sngDiscount
| intCandyBars \ intNumPeople
| intCandyBars Mod intNumPeople
| |
---|
sngAnswer = 6 - 3 * 6 / 9 |
---|
sngAnswer = (6 - 3) * (6 / 9) |
---|
exponentiation
multiplication and division (as they occur from left to right)
| integer division
| modulus division
| addition and subtraction (as they occur from left to right)
| |
---|
More on Assignment Statements |
---|
intTotal = intTotal + intAmount |
---|
intCount = intCount + 1 |
---|
intA=2 intB=4 intC=3 intA = intA + intB intC = intC + 1 intA = intA + intC |
---|
VB | C
intC = intC + 1
| intC++
| intC = intC - 1
| intC--
| intA = intA + intB
| intA += intB
| intA = intA - intB
| intA -= intB
| intA = intA * intB
| intA *= intB
| intA = intA / intB
| intA /= intB
| |
---|
Multiply Hours by Rate giving Gross
1 to Counter giving Counter
| |
---|
Sequence Control Structure |
---|
Sequence
Selection
| Iteration also called repetition
| |
---|
FlowChart |
---|
Walking Though Code |
---|
Dim intA as integer | Dim intB as integer
|
|
|
|
| | Dim sngC as single
|
|
|
|
| | Dim sngD as single
|
|
|
|
| |
| intA
| intB
| sngC
| sngD
| Output
| intA = 5
|
|
|
|
| | intB = 10
|
|
|
|
| | sngD = 2.4
|
|
|
|
| | | Print "sngC = ", sngC
|
|
|
|
| |
|
|
|
|
|
| intA = sngD
|
|
|
|
| | intB = intA * intB
|
|
|
|
| | Print "intB = ", intB
|
|
|
|
| | sngC = intA * intB - intA
|
|
|
|
| | sngD = sngC / 2
|
|
|
|
| | Print "sngC = ", sngC
|
|
|
|
| | sngD = sngD + intA + intB
|
|
|
|
| | Print "sngD = ", sngD
|
|
|
|
| | |
---|
Val() and Conversion Functions |
---|
variable/property = functionName(argument1, argument2,etc) |
---|
Dim sngHoldnum as single sngHoldnum = Val(txtInput.Text) |
---|
intNumber = Val("nonnumeric") Print intNumber 'output - 0 |
---|
intNumber = Val("98junk") Print intNumber 'output - 98 |
---|
intNumber = Val("junk98") Print intNumber 'output - 98 |
---|
Dim intYear as Integer intYear = Val(txtYear.Text) |
---|
Str(expression)
CBool(expression)
| CDate(expression)
| CDbl(expression)
| CInt(expression)
| CLng(expression)
| CSng(expression)
| CStr(expression)
| |
---|
Dim lngAnswer as long lngAnswer = 24 * 24 * 60 |
---|
Because Visual Basic will attempt to store intermediate results in an integer since all operands in the expression are integers. (24 * 24 * 60 = 34,560 which is larger than an integer can hold)
lngAnswer = CLng(24) * 24 * 60 |
---|
Visual BASIC Functions |
---|
A | E | IsNull | PPmt | TypeName
|
| IsNumeric
| PV
| | Abs
| Environ
| IsObject
|
| U
| Array
| EOF
|
| O
|
| Asc
| Error
| L
|
| UBound
| AscB
| Exp
|
| OBColor
| UCase
| Atn
|
| LBound
|
|
|
| F
| LCase
| R
| V
| C
|
| Left
|
|
|
| FileAttr
| Len
| Rate
| Val
| CBool
| FileDateTime
| LoadPicture
| ReadProperty
| VarType
| CByte
| FileLen
| LoadResData
| RGB
|
| CCur
| Fix
| LoadResPicture
| Right
| W
| CDate
| Format
| LoadResString
| Rnd
|
| CDbl
| FreeFile
| Loc
| RTrim
|
| Choose
| FV
| LOF
|
| Weekday
| Chr
|
| Log
| S
|
| ChrB
| G
| LTrim
|
| Y
| CInt
|
|
| Second
|
| CLng
| GetAllSettings
| M
| Seek
| Year
| Command
| GetAttr
|
| Sgn
|
| Cos
| GetObject
| Mid
| Shell
|
| CreateDatabase
| GetSetting
| Minute
| Sin
|
| CreateObject
|
| MIRR
| SLN
|
| CSng
| H
| Month
| Space
|
| CStr
|
| MsgBox
| Spc
|
| CurDir
|
|
| Sqr
|
| CVar
| Hex
| N
| Str
|
| CVErr
| Hour
|
| StrComp
|
|
|
| Now
| StrConv
|
| D
| I
|
| String
|
|
|
| NPer
| Switch
|
| Daate
| Ilf
| NPV
| SYD
|
| DateAdd
| IMEStatus
|
|
|
| DateDiff
| Input
|
|
|
| DatePart
| InStr
| O
| T
|
| DateSerial
| Int
|
|
|
| DateValue
| IPmt
| Oct
| Tab
|
| Day
| IRR
| OpenDatabase
| Tan
|
| DDB
| IsArray
|
| Time
|
| Dir
| IsDate
| P
| Timer
|
| DoEvents
| IsEmpty
|
| TimeSerial
|
|
| IsError
| Partition
| TimeValue
|
|
| IsMissing
| Pmt
| Trim
|
| |
---|
Focus |
---|
Private Sub cmdClear_Click() TxtName.Text = "" TxtAddress.Text = "" TxtName.SetFocus End Sub |
---|
Format Function |
---|
Format(variable/object, "format name") |
---|
Format name | Description
General Number
| Display number with no thousand separators and no fixed number of decimal postions.
| Currency
| Display number with thousand separators, if appropriate; display two digits to the right of the decimal separator. Output is based on system locale settings.
| Fixed
| Display at least one digit to the left and two digits to the right of the decimal separator. Does not display thousand separators.
| Standard
| Display number with thousand separators, at least one digit to the left and two digits to the right of the decimal separator.
| Percent
| Display number multiplied by 100 with a percent sign (%) appended to the right; always display two digits to the right of the decimal separator.
| Scientific
| Use Standard Scientific Notation
| Yes/No
| Display No if number is 0; otherwise, display Yes.
| True/False
| Display False if number is 0; otherwise, display True.
| On/Off
| Display Off if number is 0; otherwise, display On.
| |
---|
sngAmount = 100 lblAmtOut.caption = Format(sngAmount,"currency") |
---|
Format Name | Description
General Date
| Display a date and/or time. For real numbers, display a date and time, for example, 4/3/93 05:34 PM. If there is no fractional part, display only a date, for example, 4/3/93. If there is no integer part, display time only, for example, 05:34 PM. Date display is determined by your system settings.
| Long Date
| Display a date according to your system's long date format.
| Medium Date
| Display a date using the medium date format appropriate for the language version of the host application.
| Short Date
| Display a date using your system's short date format.
| Long Time
| Display a time using your system's long time format; includes hours, minutes, seconds.
| Medium Time
| Display time in 12-hour format using hours and minutes and the AM/PM designator.
| Short Time
| Display a time using the 24-hour format, for example, 17:45.
| |
---|
dtmDate = #02/28/2004# lblDateOut.caption = Format(dtmDate, "long date") |
---|
Function | Output
Format (12345.628, "Standard")
| 12,345.63
| Format (12345.628, "Currency")
| $12,345.63
| Format (12345.628, "#,0")
| 12,346
| Format (.628, "Percent")
| 62.80%
| Format (12345.628, "Scientific")
| 1.23E+04
| Format (1 / 4, "Standard")
| 0.25
| Format (2 + 3.759, "Currency")
| $5.76
| Format (-1234, "Standard")
| -1,234.00
| Format (-1234, "Currency")
| ($1,234.00)
| Format (".2", "Currency")
| $0.20
| Format ("7/4/04", "Long Date")
| Thursday, July 4, 2004
| Format ("7/4/04, "Medium Date")
| 04-Jul-04
| |
---|
FormatCurrency(curamount,[# of decimal postions]) Note: Arguments enclosed in square brackets are optional |
---|
sngAmount = 100 lblAmtOut.caption = FormatCurrency(sngAmount) lblAmtOut.caption = FormatCurrency(sngAmount,0) |
---|
Function | Returns
FormatCurrency (12345.628)
| $12,345.63
| FormatCurrency (12345.628, 0)
| $12,346
| FormatCurrency (345.645)
| $345.65
| FormatCurrency (345)
| $345.00
| FormatCurrency (12345.6)
| $12,345.60
| |
---|
FormatDateTime(Date[,NamedFormat]) |
---|
Constant | Value | Description
vbGeneralDate
| 0
| Display a date and/or time. If there is a date part, display it as a short date. If there is a time part, display it as a long time. If present, both parts are displayed.
| vbLongDate
| 1
| Display a date using the long date format specified in your computer's regional settings.
| vbShortDate
| 2
| Display a date using the short date format specified in your computer's regional settings.
| vbLongTime
| 3
| Display a time using the time format specified in your computer's regional settings.
| vbShortTime
| 4
| Display a time using the 24-hour format (hh:mm).
| |
---|
dtmDate = #02/28/2004# lblDateOut.caption = FormatDateTime(dtmDate, vblongdate) |
---|
Pseudocode |
---|
Get FirstName from textbox Input Year from textbox |
---|
Print "Name is", FirstName on screen Display Name is", FirstName in label Output EmployeeInformation to Printer |
---|
Compute OvertimeHours = Hours – 40 Calculate GrossPay = Hours * PayRate |
---|
Add Hours To TotalHours Subtract FICAAmount from GrossPay |
---|
Inputting value from external source (covered above).
Store the result of a calculation (also covered above).
| Initializing, Reinitializing can be indicate by Let or initialize or reinitialize
| Save a value for later use. To indicate storing a value for later use we can use words like Store, Save, Hold.
| |
---|
Let the FICARate = .0768 Initialize StateTax Rate to .03 |
---|
Let EmployeeDeductions = 0 Reinitialize OvertimeHours to 0 |
---|
Flowchart |
---|
Simple Visual Basic If Statement |
---|
If condition Then statement |
---|
If condition Then statement statement statement End if 'End If is two words |
---|
If txtinput.Text = "" Then Print "you must enter a value in the text box" End If |
---|
= | Equal to
>
| Greater than
| <
| Less than
| <>
| Not equal to
| >=
| Greater than or Equal to
| <=
| Less than or Equal to
| |
---|
If 6 then Print "this is true" End if |
---|
Dim blnFlag as Boolean : : : If blnFlag then 'blnFlag is either True or False Print "the flag is on" Else Print "the flag is off" End if |
---|
If intAge >= 18 then Print “Able to Vote” End If |
---|
If intScore = 100 then Print “Perfect Score” End If |
---|
If intAge < 21 then Print “underage” End If |
---|
Order of ASCII exercise |
---|
Dave
5
| five
| America
| David
| carport
| DAVID
| $100
| Amy Sue
| AmySue
| (A Comment)
| zoo
| car
| 100
| <insert name>
| |
---|
Simple If Exercise |
---|
Code | Output
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
---|
If Else |
---|
If condition Then statement statement statement Else statement statement End If |
---|
If txtInput.Text = "" Then Print "you must enter a value in the text box" Else 'Will be executed when txtInput.Text is NOT = "" Print "you entered "; txtInput.Text End If |
---|
If intTestScore > 69 Then strGrade = "Pass" Else strGrade = "Fail" End If If intTestScore > 69 Then strGrade = "Pass" End If If intTestScore <= 69 Then strGrade = "Fail" End If |
---|
If sngHours <= 40 Then sngRegular = sngHours * sngRate sngOvertime = 0 Else sngRegular = 40 * sngRate sngOvertime = (sngHours – 40) * (sngRate * 1.5) End if If sngHours <= 40 Then sngRegular = sngHours * sngRate sngOvertime = 0 End If If snghours > 40 Then sngRegular = 40 * sngRate sngOvertime = (sngHours – 40) * (sngRate * 1.5) End if |
---|
If intTicketsSold = intTicketsAvailable Then Print “Sold Out” Else Print “Tickets Available” End If If intTicketsSold = intTicketsAvailable Then Print “Sold Out” End If If intTicketsSold <> intTicketsAvailable Then Print “Tickets Available” End If |
---|
Selecting Text in Text boxes |
---|
Private Sub txtInput_GotFocus() txtInput.SelStart = 0 txtInput.SelLength = Len(txtInput.Text) End Sub |
---|
Elseif |
---|
Input Age If Age < 6 then School = "Preschool" ElseIf Age < 14 School = "Elementary" ElseIf Age < 18 then School = "Secondary" Else School = "Post secondary" End If Report School |
---|
If condition then statement statement ElseIf condition then statement statement statement ElseIf condition then statement statement statement Else statement statement statement End if |
---|
If txtinput.Text = "" Then Print "you must enter a value in the text box" ElseIf IsNumeric(txtinput.Text) Then Print "you entered the number "; txtinput.Text Else Print "you entered the string "; txtinput.Text End If |
---|
If sngSales < 1000 then sngCommissionRate = .10 ElseIf sngSales < 5000 then sngCommissionRate = .11 ElseIf sngSales < 10000 then sngCommissionRate = .12 Else sngCommissionRate = .13 EndIf |
---|
If strEmployeeCode = "S" then strStatus = "Salaried" ElseIf strEmployeeCode = "H" then strStatus = "Hourly" Else strStatus = "Contractual" End If |
---|
If strEmployeeCode = "S" then strStatus = "Salaried" Else If strEmployeeCode = "H" then strStatus = "Hourly" Else strStatus = "Contractual" End If |
---|
If strEmployeeCode = "S" then strStatus = "Salaried" Else If strEmployeeCode = "H" then strStatus = "Hourly" Else strStatus = "Contractual" End If End If |
---|
If strEmployeeCode = "S" then strStatus = "Salaried" ElseIf strEmployeeCode = "H" then strStatus = "Hourly" Else strStatus = "Contractual" End If |
---|
Visual Basic Message Box |
---|
Indicate invalid data entry | You must enter numeric data for Hour Worked
Confirm an action
| Do you really want to exit program?
| Warn of possible consequence of the user action
|
If you exit without saving your file you will lose your changes
| Keep the user informed
| File sent to printer
| |
---|
Msgbox strMessage [,,strTitle] |
---|
MsgBox "this is a message" |
---|
Dim strMessage as string strMessage = "this is a message” MsgBox strMessage, , "Demo Message Box" |
---|
Dim strMessage As String strMessage = "This message will" _ & vbNewLine _ & "appear on two lines" MsgBox strMessage, , "Demo Message Box" |
---|
White Space |
---|
Guidelines for adding white space |
---|
Indent all statements within procedures at least one tab stop.
Separate each group of like or related statements with a blank line.
(for example add blank lines between Procedures, after Dim statements, after
input statements)
| Use the continuation operator _ to continue long statement from one
line to the next. Use continuation so that you can see all the code on the
screen without scrolling to the right and to prevent lines from wrapping on
their own when printed. Break lines at logical points.
| |
---|
Indent lines that are continued from the previous line.
Line each If up with its matching, Else, ElseIf and End IF.
| Indent all subordinate statements within an If statement.
Precede and follow each If statement block with a blank line.
| Indent nested IF.
| |
---|
Nested If Selection Structure |
---|
Get Student Name Get Grade Point Average from User Get Hours Completed from User If Grade Point Average is greater than 3.5 then If Hours Completed is greater than or equal to 15 then Display Student Name " is Honor Student" End If End If |
---|
Get Age from voter If Age is greater than 17 then Get Registration Status from voter If voter is registered then Display "You may Vote" Else Display "You must register to vote" End If Else Display "You are too young to vote." End If |
---|
Nested If |
---|
If condition Then If condition Then statement statement End if End if |
---|
blnHonorStudent = False If intGPA > 3.5 then If intHoursCompleted >= 15 then blnHonorStudent = true End if End if Print blnHonorStudent |
---|
sngBonus will be assigned the value of 1000 only if both conditions are true
If sngSales is greater than 300000 BUT intYearsEmployed is NOT greater than 2 sngBonus will be made equal to 500.
Notice if sngSales is NOT greater than 300000 no value is placed in sngBonus.
sngBonus = 0 If sngSales > 300000 Then If intYearsEmployed > 2 Then sngBonus = 1000 Else sngBonus = 500 End If End If Print sngBonus |
---|
If intAge is greater than 17 BUT blnRegistered is not True the message "You must register to vote " will be displayed.
If intAge is NOT greater than 17 the variable blnRegistered will not be tested. The message "You are too young to vote" will be displayed.
If intAge > 17 Then If blnRegistered Then lblMessage.caption = "You may vote" Else lblmessage.caption = "You must register to vote" End If Else lblmessage.caption = "You are too young to vote" End If |
---|
If BOTH conditions are true a new sngBbalance and sngAmtWithdrawa l will be calculated.
If sngAmtWithdrawal <= sngBalance BUT the withdrawal combined with recent withdrawals will exceed the limit the withdrawal is denied.
If there is not enough money to cover the withdrawal the withdrawal is denied, the test for exceeding the limit is not checked.
If sngAmtWithdrawal <= sngBalance Then If sngAmtRecentWithdrawal + sngAmtWithdrawal <= 500 then sngBalance = sngBalance - sngAmtWithdrawal sngAmtRecentWithdrawal = sngAmtRecentWithdrawal + sngAmtWithdrawal Else sngAmtWithdrawal = 0 End If Else sngAmtWithdrawal = 0 End If Print "Amount current withdrawal = " & sngAmtWithdrawal Print "Total recent withdrawals = " & sngAmtRecentWithdrawal Print "New Balance = " & sngBalance |
---|
How deep is too deep? |
---|
If blnSalaried = False Then If intYearsEmployed > 5 Then If sngMonthSales > 200000 Then If sngLastMonthSales > 200000 Then sngCommission = sngMonthSales * .10 Else sngCommission = sngMonthSales * .8 End If Else sngCommission = sngMonthSales * .6 End If Else sngCommission = sngMonthSales * .04 End If Else sngCommission = sngMonthSales * .05 End If |
---|
If blnSalaried = True Then sngCommission = sngMonthSales * .05 ElseIf intYearsEmployed <= 5 Then sngCommission = sngMonthSales * .04 ElseIf sngMonthSales > 200000 Then If sngLastMonthSales > 200000 Then sngCommission = sngMonthSales * .10 Else sngCommission = sngMonthSales * .8 End If Else sngCommission = sngMonthSales * .6 End If |
---|
Input Data Validation |
---|
Testing for blank entry fields
Testing for nonnumeric data
| Testing for values within acceptable ranges
| Testing for values that are within a predetermined set of values.
| |
---|
IsNumeric(variable, constant, or expression) evaluates to a number. or expression does not evaluate to a number. |
---|
IF IsNumeric(txtIncome.Text) = False then MsgBox "You must enter a valid number for income" lblTax.Caption = "" 'do not displace any thing displayed in the output label for invalide data Else sngIncome = val(txtIncome.text) If sngIncome > 30000 then sngTax = 4500 + ((sngIncome – 30000) * .28) Else sngTax = sngIncome * .15 EndIf lblTax.Caption = FormatCurrency(sngTax) the test for numeric input, It is NOT controlled by the test of sngIncome. End If |
---|
Using BreakPoints |
---|
Frequently erroneous assumptions on our part send us down the wrong path of the program logic.
You can step through your code by setting a BreakPoint and then watch as each statement is executed.
1) Click the gray margin beside a statement prior to where you believe
the problem occurs.
For our programs it is usually best to set the breakpoint at the top of the
procedure,
on the first line after the Dim statements. A reddish dot will appear in the
margin.
This breakpoint indicates that execution of the code will pause when it
reaches this statement.
2) Run the program, enter input values that produce the incorrect
output,
and click the appropriate command button
| 3) Execution will be suspended at the breakpoint. The program will be
in Break mode
and the statement will be highlighted in yellow.
A statement highlighted in yellow has not yet been executed.
| 4) At this point you should use your mouse (point at each variable or
property in
the statement) to ascertain the current value of each operand.
A data tip will pop up to display the current value.
| ♦ a. Are the values what you expected them to be? 5) Based on the values of the operands evaluate the expression a
nd decide what you think will happen
| a. if is in an assignment statement determine the value that will be storedb. if it is an If statement determine the next statement that will be executed♦ NOTE: it is VERY IMPORTANT that you THINK about what will happen before you move on 6) Press the F8 key. This will move execute the highlighted statement
and
move the highlight to the next statement to be executed.
| a. If the previously highlighted statement was an assignment statement point at the variable that received a new valuei. Is the value what you expected it to be?
b. If the previously highlighted statement was an If statement
did the highlighted move to the statement you expected it to?
| |
---|---|---|---|---|---|---|
7) Repeat steps 4 - 6 until the end of the procedure or you have found the error. |
Logical operators and compound If statements |
---|
If sngSales > 300000 Then If intYearsEmployed > 4 then sngCommission =sngSales * .03 Else sngCommission = sngSales * .02 End If Else sngCommission = sngSales * .02 End If |
---|
If sngSales > 300000 Then sngCommission =sngSales * .03 elseIf intYearsEmployed > 4 then sngCommission =sngSales * .03 Else sngCommission = sngSales * .02 End If |
---|
sngCommission = 0 If sngSales > 300000 Then If blnManagement Then Else sngCommission = sngSales * .03 End If End If |
---|
If (condition) And (condition) then statement statement statement end if |
---|
If sngSales > 300000 And intYearsEmployed > 4 then sngCommission = sngSales * .03 Else sngCommission = sngSales * .02 End If |
---|
Sales > $300.000 And Years employed > 4 |
---|
1st Condition | 2nd Condition | Statement
A
| B
| A and B
| true
| true
| true
| true
| false
| false
| false
| true
| false
| false
| false
| false
| |
---|
If sngYearsEmployed > 4 _ And sngSales > 300000 _ And sngPreviousSales > 300000 then sngCommission = sngSales * .03 Else sngCommission = sngSales * .02 End If |
---|
Years employed > 4 And Sales > $300.000 And Previous Sales > $300,000 |
---|
1st Condition | 2nd Condition | 3rd Condition | Statement
A
| B
| C
| A and B and C
| true
| true
| true
| true
| true
| true
| false
| false
| true
| false
| true
| false
| true
| false
| false
| false
| false
| true
| true
| false
| false
| false
| true
| false
| false
| true
| false
| false
| False
| False
| false
| false
| |
---|
If sngSales > 100000 And < 300000 then sngCommission = sngSales * .03 End If |
---|
The Or operator |
---|
If (condition) Or (condition) then statement statement statement End if |
---|
If sngSales > 300000 Or intYearsEmployed > 4 then sngCommission = sngSales * .03 Else sngCommission = sngSales * .02 End If |
---|
Sales > $300.000 Or Years employed > 4 |
---|
1st Condition | 2nd Condition | Statement
A
| B
| A or B
| true
| true
| true
| true
| false
| true
| false
| true
| true
| false
| false
| false
| |
---|
If sngSales > 300000 _ Or intYearsEmployed > 4 _ Or blnManagement then sngCommission = sngSales * .03 Else sngCommission = sngSales * .02 End If |
---|
Years employed > 4 Or Sales > $300.000 Or is Management |
---|
1st Condition | 2nd Condition | 3rd Condition | Statement
A
| B
| C
| A or B or C
| true
| true
| true
| true
| true
| true
| false
| true
| true
| false
| true
| true
| true
| false
| false
| true
| false
| true
| true
| true
| false
| false
| true
| true
| false
| true
| false
| true
| False
| False
| false
| false
| |
---|
Not operator |
---|
If Not (Condition) then Statement Statement End if |
---|
sngCommission = 0 If sngSales > 300000 If Not blnManagement then sngCommission = sngSales * .03 End If End If |
---|
sngCommission = 0 If sngSales > 300000 If blnManagement Else sngCommission = sngSales * .03 End If |
---|
Hierarchy of Logical Operators |
---|
Given intYearsEmployed = 6 sngSales = 300500 sngPreviousSales = 250000 If intYearsEmployed > 4 _ Or sngSales > 300000 _ And sngPreviousSales > 300000 sngCommission = sngSales * .03 Else sngCommission = sngSales * .02 End If |
---|
If intYearsEmployed > 4 _ Or (sngSales > 300000 And sngPreviousSales > 300000) Then sngCommission = sngSales * .03 Else sngCommission = sngSales * .02 End If |
---|
If (intYearsEmployed > 4 Or sngSales > 300000) _ And (sngPreviousSales > 300000) Then |
---|
Case Structure Pseudocode |
---|
Input a Grade If the Grade = 100 then Report "Perfect Score" ElseIf the Grade > 89 then Report "Grade = A" ElseIf the Grade > 79 then Report "Grade = B" ElseIf the Grade > 69 then Report "Grade = C" ElseIf the Grade > 59 then Report "Grade = D" Ese Report "Grade = F" End if |
---|
Input a Grade Case based on Grade Case 100 Report "Perfect Score" Case > 89 Report "Grade = A" Case > 79 Report "Grade = B" Case > 69 Report "Grade = C" Case > 59 Report "Grade = D" Default Report "Grade = F" End Case |
---|
Select Case Statement in Visual Basic |
---|
Select Case testexpression [Case expressionlist1 statementblock] [Case expressionlist2 statementblock] [Case Else statementblock] End Select |
---|
a value | Case 1
a list of values
| Case "red", "yellow"
| a range of values
| Case 1 to 10
| a comparison
| Case Is > 5
| a combination
| Case 1, 4 to 5, is > 10
| |
---|
intGrade = Val(txtGrade.Text) Select Case intGrade Case 100 'equality Implied lblGrade.caption = "Perfect Score" Case Is > 89 'The word Is is required with relational operators lblGrade.caption = "Grade = A" Case 80 To 89 'specific range identified lblGrade.caption = "Grade = B" Case Is > 69 lblGrade.caption = "Grade = C" Case Is > 59 lblGrade.caption = "Grade = D" Case Else lblGrade.caption = "Grade = F" End Select |
---|
Counter & Accumulators |
---|
Dim intCount as integer Private sub cmdCount_click() intCount = intCount + 1 End Sub Private sub cmdReportCount_click() Print intCount End Sub |
---|
A = A + 1 (where A is an integer variable) |
---|
1. Declare a variable to hold the Accumulated Value
2. Repeatedly execute a statement that adds each desired
value to the accumulator variable
| 3 To add up values enter in a text box
| |
---|
Dim sngTotal as Single Private sub cmdAddIt_click() Dim sngNumber as Single sngNumber = Val(txtNumber.Text) sngTotal = sngTotal + sngNumber End Sub -------------------------------------- Private sub cmdReportCount_click() Print sngTotal End Sub |
---|
A = A + B |
---|
Private sub cmdCount_click() intCount = intCount + 1 lblCounting.Caption = lblCounting.Caption _ & " " & intCount End Sub |
---|
A = A & " " & B |
---|
Scope |
---|
Procedures
Declarations section
| |
---|
Private sub cmdPrintMess_Click() Dim intNumber as Integer intNumber = intNumber + 5 Print intNumber End Sub |
---|
Private sub cmdPrintTheNumber_Click() Print intNumber End Sub |
---|
Private sub cmdprintmess_click() Static intNumber as integer intNumber = intNumber + 5 Print intNumber End Sub |
---|
Option Explicit Dim intNumber As Integer intNumber = 5 |
---|
Private sub Form_Load() dblMaxLoanAmt = 1000000 dblMaxInterestRate = .25 End Sub |
---|
Division by Zero |
---|
If intDivisor <> 0 then sngAnswer = intDividend / intDivisor End If |
---|
Pseudocode Iteration Control Structure |
---|
Counter = 1 Do as long as Counter is <= 10 Print counter Counter = Counter + 1 End loop |
---|
Counter = 1 Total = 0 Do until Counter > 10 Total = Total + Counter Output "Sum of numbers between 1 and " & Counter & " = " & Total Counter = Counter + 1 End Loop Output Total |
---|
Charting Multiple Statements Inside a Loop |
---|
Iteration (Do Loop) |
---|
Do While condition : Statements to execute while condition is true : Loop Next instruction |
---|
Do : Statements to execute while condition is true : Loop While condition Next instruction |
---|
Do until condition : Statements to execute until condition is true : Loop Next instruction |
---|
Do : Statements to execute until condition is true : Loop until condition Next instruction |
---|
While | The instructions inside loop will be executed as long as the condition is True.
Until
| The instructions inside loop will be executed as long as the condition is False.
| |
---|
intCount = 0 | intCount = 0
Do While intCount <> 3
| Do Until intCount = 3
| intCount = intCount + 1
| intCount = intCount + 1
| Print intCount
| Print intCount
| Loop
| Loop
| |
The following code don't stop
Dim intCount as integer intCount = 1 Do until intCount = 100 Print intCount intCount = intCount + 2 Loop |
---|
Do Print Loop |
---|
Random Numbers |
---|
Dim intRandomNumber as integer intRandomNumber = rnd() * 100 |
---|
Dim intRandomNumber as integer Randomize intRandomNumber = rnd() * 100 Visual Basic Input Box |
---|
InputBox |
---|
variable = InputBox("a prompt", ["title"]) |
---|
intNum = InputBox("Enter a number", "input box") |
---|
Iteration Control Structure in Visual Basic |
---|
For loopVariable = StartValue To StopValue Step StepValue one or more VB instructions Next loopVariable |
---|
For intx = 1 To 10 Step 1 Print intx Next intx Print "the end" |
---|
1) The loop variable is initialized to the Start Value .
2) The loop variable is compared to the stop value.
|
When the loop variable becomes greater than the stop value the
loop has been satisfied
and control passes to the statement following the Next intX statement.
|
---|
There are several ways you can think about whether the statements inside the loop are going to be executed. The statements will be execute
For intNum = 1 To 10 Print intNum Next Print "The End" |
---|
For intNum = 10 To 0 Step -1 Print intNum Next intNum Print "The End" Print intNum |
---|
For intNum = 10 To 100 Step 10 Print intNum Next intNum Print "The End" Print intNum |
---|
What do you think will happen with the following loop?
For intNum = 12 To 1 Step 2 Print intNum Next intNum |
---|
For intNum = 1 To 10 Step 0 Print intNum Next intNum |
---|
intBegin = 1 For intNum = intBegin To intStop Step 1 Print intNum Next intNum |
---|
For intRow = 1 to 3 step 1 For intCol = 1 to 3 step 1 print "*"; Next intCol Print Next intRow Print "The End" |
---|
Converting Flowchart/Pseudocode to VB Code |
---|
If your Pseudocode is as follows | Given the For...Next loop format
|
|
|
---|
1. The loop control variable is initialized
2. The loop control variable is compared to the stop value
| 3. The loop control variable is incremented by the step value
| |
---|
|
|
Problematic Code | Healthy Code
|
|
|
---|
General Procedures |
---|
Event procedures | tell objects how to respond to events.
General procedures
| General procedures are programmer defined.
| |
---|
Sub procedures
Function procedures
| |
---|
Function
GoSub
| Method
| Module
| Paragraph
| Predefined Process
| Procedure
| Subroutine
| |
---|
They make it easier to see "the big picture" by placing detail
level instructions away from the skeleton (the main logic) of the program.
Different programmers can be assigned the task of creating subroutines.
| Subroutines may be called from multiple places in
a program or reused in other programs.
| |
---|
When creating subroutines each subroutine should be charged with one
basic task.
You should be able to describe the purpose of the subroutine in the name
of the subroutine.
| You, the programmer, supply the names for subroutines.
give your procedures names that are descriptive.
| A good rule to follow is the verb-noun or verb-adjective-noun guideline.
|
---|
Private Sub InitializeVariables() : : End sub |
---|
Call InitializeVariables |
---|
InitializeVariables |
---|
Private Sub Form_Load() Call InitializeVariables txtName.SetFocus 'this line will be executed after the InitializeVariables procedure is completed : : |
---|
Subroutines are used to break complex sections of code into smaller
more manageable pieces and to prevent very long procedures.
Any time you find the need for 3 or more statements to be repeated in
your program you should consider using a subroutine.
| |
---|
Tools / Add Procedure |
---|
A shell of a procedure will be created
Private Sub InitializeVariables() End Sub |
---|
Pseudocodeing and Flowcharting General Procedures |
---|
Main Procedure Get Purchase amount from user Get Membership status from user If purchase amount invalid Display error message Else If member Call calculate member discount procedure Else Call calculate nonmember discount procedure End if End if End Main Procedure |
---|
Calculate Member Discount Procedure If Purchase <= 100 Discount = purchase * .1 Else Discount = (purchase * .1) + (purchase – 100 * .05) End if Display discount End Calculate Member Discount Procedure |
---|
Calculate NonMember Discount Procedure If Purchase >= 100 Discount = (purchase * .1) Else Discount = 0 End if Display discount End Calculate NonMember Discount Procedure |
---|
Flowchart using general procedures |
---|
Passing Arguments to Procedures |
---|
: Call TotalSales (sngSaleAmount) 'will pass sngSalesAmount to TotalSales : |
---|
: TotalSales sngSaleAmount : |
---|
Call TotalSales (sngSaleAmount, dblTotalSales) |
---|
Call CalculateFICA (sngGrossPay) |
---|
Private sub CalculateFICA (sngPay as single) : : End sub |
---|
Call TotalSales (sngSaleAmount, dblTotalSales) |
---|
Private sub TotalSales (sngSaleAmount as Single, dblTotalSales as Double) : End sub |
---|
Private sub CalculateFICA (ByVal sngPay as single) sngFICA = pay * .06875 : : End Sub |
---|
Data Files & Data Hierarchy |
---|
Executables (.exe)
System files (.dll, .sys, .ini, etc.)
| Documents (word files, PowerPoint, etc.)
| Source code files (.frm, .bas)
| Data Files (files that contain facts about people or things)
| |
---|
A file is a collection of related records. (Employees, videos, accounts,
etc.)
Each record is composed of fields and contains all the
information about one object. (Employee, video, account)
| Each field contains one piece of information about the object
(name, address, title, artist, etc.) and is composed of characters,
each of which usually requires 1 byte of storage.
| |
---|
#2006-11-20#,"couch",112.25 #2006-11-20#,"couch",12.25 #2006-11-20#,"hoyne",125.5 #2006-11-20#,"thompson",58.25 #2006-11-21#,"Couch",15.25 |
---|
Sequential Data Files |
---|
Data is stored in files.
Files are stored on disk (usually).
| Files are made up of records.
| Records are made up of fields.
| |
---|
Open the file
Read or Write to the file
| Close the file when it is finished.
| |
---|
Open "path\filename" for mode as #filenum |
---|
Open "a:\input.dat" for input as #1 |
---|
strFileName = "f:\myfile.txt" Open strFileName for input as #1 |
---|
Write to a Sequential Data Files |
---|
Write #1, data1, data2, data3 |
---|
: Dim strName as string Dim strPhone as string strName = "George" strPhone = "356-8932" open "a:\input.dat" for output as #1 write #1, strName, strPhone |
---|
Write #1, txtName.text, txtPhone.text |
---|
Close a Sequential Data Files |
---|
Close #1 |
---|
Close |
---|
Read from a Sequential Data Files |
---|
We use the input statement to read from a data file.
We must provide a variable for every data element read.
Those variables must of course be defined.
Input #1, var1, var2, var3 |
---|
: Dim strName as string Dim strPhone as string open "a:\input.dat" for input as #1 Input #1, strName, strPhone |
---|
Do While Not EOF(1) Input #1, strName, strPhone : loop |
---|
Date Function |
---|
The statement
Print Date |
---|
Dim dtmDateSale as Date |
---|
dtmDate = #06/30/1950# |
---|
Reports |
---|
Used by management
Used in presentations
| For control or audit purposes
| |
---|
Transaction information
Time card information
| Information about a particular sale
| A grade to be posted
| A credit card payment
| Bank deposit
| Master Information
| Employee information including Year To Date information
| Savings account information. (Balance, YTD interest paid, Date last
deposit)
| Summary Information
| Total payroll this pay period
| Average daily sales total
| Report organization
| |
---|
Report Header | The report header contains items which print only once,
at the top (or beginning) of a report.
Current Date
| The current date is often included in the report header.
| Page Footer
| The page header contains items which print only once,
at the top of EACH page. Usually the items are column headings,
which label what data is in each column on the report.
The date and a page number can be included in the page header.
| Report Footer
| The report footer contains items which print only once,
at the bottom of a report, like a grand total amount at the
bottom of the last page.
| Page Footer
| The page footer contains items which print only once,
at the bottom of each page. Usually the page footer
contains a page number.
| Detail Lines
| Detail lines contain data from the records in a file...one line
per record. The detail lines can be grouped under control
break headers. A page break will occur when there are more
records in the file than will fit on a page.
| |
---|
Method of Layout Design |
---|
11 ABC Company 4 4 12 Date Name Hours Worked 10 20 5 Xx/xx/xxxx x---x xx.xx |
---|
10 + 20 + 12 (use 12 because the column heading is wider than the data.) ----------------- 42 |
---|
80 - 42 = 38 (white spaces) |
---|
38 / 4 = 9 (Width of white space block) with 2 positions left over which I will add to the right and left margin. |
---|
(34 spaces) 11 (35 spaces) ABC Company 4 4 12 Date Name Hours Worked 10 20 5 (10 spc) Xx/xx/xxxx (9 spc) x---x (9 + 3 spc) xx.xx (4 + 10 spc) |
---|
10 (the width of the data) - 4 (the width of the heading -------- 6 / 2 = 3 (the number of spaces to print before the heading) |
---|
20 (the width of the data) - 4 (the width of the heading -------- 16 / 2 = 8 (the number of spaces to print before the heading) |
---|
(34 spaces) 11 (35 spaces) ABC Company 4 4 12 (10 + 3 spaces) Date(3 + 9 + 8 spaces) Name (8 + 9 spaces) Hours Worked(10 spaces) 10 20 5 (10 spc) Xx/xx/xxxx (9 spc) x---x (9 + 3 spc) xx.xx (3 + 1 + 10 spc) |
---|
34 + 11 + 35 ----------------- 80 |
---|
10 + 3 + 4 + 3 + 9 + 8 + 4 + 8 + 9 + 12 + 10 ---------------- 80 |
---|
10 + 10 + 9 + 20 + 9 + 3 + 5 + 3 + 1 + 10 ------------------ 80 |
---|
(34 spaces) 11 (35 spaces) ABC Company 4 4 12 (10 + 3 spaces) Date(3 + 9 + 8 spaces) Name (8 + 9 spaces) Hours Worked(10 spaces) 10 20 5 (10 spc) Xx/xx/xxxx (9 spc) x---x (9 + 3 spc) xx.xx (3 + 1 + 10 spc) |
---|
1) you must use a mono-spaced font
2) you must use fixed length string when printing the column data
Discussed later or here -> Printing variable length fields in fixed
length columns
|
⊕ Printer Object♦ To control the default printer we use the Printer object.♦ The print method is used to send output to the printer.
⊕ Positioning Output on the PrinterThere are several options to choose from when controlling the spacing of printed output. For our purposes the first two methods are the best choices.♦ 1) You can control the position of the output by using the Space() function. The Space() function returns a string of spaces the length of the integer passed to itBoth
♦
2) You can control the position of the output using the CurrentX
and CurrentY properties of the printer object.
The CurrentX property setting is 0 at an object's left edge, and the CurrentY
property setting is 0 at its top edge. Coordinates are expressed in twips or
the current unit of measurement. A twip is a unit of measurement equal to
1/20
of a printer's point. There are approximately 1440 twips to a inch.
For example
♦
3) Another way you can control the position of the output is by using
semicolons and commas.
position.
When you use commas the next item to print will print in the next print zone. Print zones begin every 14 columns. The width of each column is an average of the width of all characters in the point size for the selected font.
I suggest using commas and/or semicolons to begin with just to get the information out to view. After successfully displaying the information you could then determine the correct spacing and change the statements to use the Space() function and concatenation.⊕ Controlling Font and FontSizeWhen attempting to design the layout of a report the font size and font t ype you choose will have a significant affect. Notice how the different fonts require different amounts of horizontal space even when the font size is the same in the following samples.
You can control the font type and size by setting the
Font and FontSize property of the printer object at
run time.
|
---|
Wwwwwwwwwwwwwwwwwwwwwwwwwwwwwww |
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiii |
Wwwwwwwwwwwwwwwwwwwwwwwwwwwwwww | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
⊕ Advancing to a New Page ♦
The NewPage method will advance to the top of the next page.
|
Printer.EndDoc |
---|
Printing Variable Length Data |
---|
Do While Not EOF(1) Input #1, strName, sngAmount Print Space(10); strName; Space(5); FormatCurrency(sngAmount) Loop |
---|
Dim strName as string. |
---|
You declare a fixed length string by specifying the amount of memory required in the Dim statement.
Dim strName as string * 20 |
---|
Dim strName As String * 20 : Do While Not EOF(1) Input #1, strName, sngAmount Print Space(10); strName; Space(5); FormatCurrency(sngAmount) Loop |
---|
Dim strName As String * 15 Dim strFormatedNumber As String * 9 : Do While Not EOF(1) Input #1, strName, sngAmount, strDepartment strFormatedNumber = FormatCurrency(sngAmount) Print Space(10); strName; Space(5); strFormatedNumber; _ Space(5); strDepartment Loop |
---|
Rset strFormatedNumber = FormatCurrency(sngAmount) |
---|
Variable Arrays |
---|
Dim strName1 as string Dim strName2 as string Dim strName3 as string |
---|
strName1 = txtName.text print strName1 strName2 = txtName.text print strName2 strName3 = txtName.text print strName3 |
---|
Variable Arrays |
---|
Print strName(1) Print strName(3) |
---|
Print strName(intSub) |
---|
Dim variablename(n to n) as datatype |
---|
Dim variablename(n) as datatype |
---|
Dim strPhoneNum(1 to 50) as string Dim strPhoneNum(0 to 49) as string Dim strPhoneNum(49) as string |
---|
Dim strPhoneNum(49) as string |
---|
The first element in the preceding array is referred to as strPhoneNum(0)
The second element is strPhoneNum(1)
| The fiftieth is strPhoneNum(49)
| The subscript indicates a displacement from the beginning of the arrays.
| |
---|
Subscript out of range |
---|
1. Initialize or load values into an array from using constants, user input or from a file.
2. Dump or printout the contents of the array.
| 3. Lookup or search an array for a particular element.
| 4. Change an array element
| |
---|
Dim strNames(24) As String Dim intIndex As Integer intIndex = 0 strNames(intIndex) = InputBox("enter a name, 'quit' to quit") Do While LCase(strNames(intIndex)) <> "quit" intIndex = intIndex + 1 strNames(intIndex) = InputBox("enter a name, 'quit' to quit") Loop Print "names in array "; intIndex |
---|
intIndex = 0 Do While LCase(strNames(intIndex)) <> "quit" Print strNames(intIndex) intIndex = intIndex + 1 Loop |
---|
Searching an Array |
---|
1. Initialize or load values into an array from using constants, user input or from a file. (Discussed on previous web page.)
2. Dump or printout the contents of the array. (Discussed on previous web page.)
|
3. Lookup or search an array for a particular element.
|
4. Change an array element
| |
---|
when you find what you are looking for
OR when you know that you will not find what you are looking for.
| |
---|
The end of the array
The last value stored in the array (the array may be declared to hold up to 25 elements but only 15 elements have actually been loaded into the array.
| |
---|
§ it finds a match OR § it finds an empty string (which we will assume means there are no other entries in the array) OR § it has looked at all 25 elements. Dim strNames(24) As String : : Do While strSearchString <> strNames(intindex) And strNames(intindex) <> “” And intindex < 24 intindex = intindex + 1 Loop If strSearchString = strNames(intindex) Then MsgBox strSearchString & " was found at location " & intindex Else MsgBox strSearchString & " not found." End If |
---|
VB Message Box Function |
---|
Indicate invalid data entry
Confirm an action
| Warn of possible consequence of the user action
| Keep the user informed
| |
---|
The format of the MsgBox function
intAnswer = MsgBox (message, [buttons], [title]) |
---|
Constant | Value | Description
vbOKOnly
| 0
| Display OK button only.
| vbOKCancel
| 1
| Display OK and Cancel buttons.
| vbAbortRetryIgnore
| 2
| Display Abort, Retry, and Ignore buttons.
| vbYesNoCancel
| 3
| Display Yes, No, and Cancel buttons.
| vbYesNo
| 4
| Display Yes and No buttons.
| vbRetryCancel
| 5
| Display Retry and Cancel buttons.
| vbCritical
| 16
| Display Critical Message icon.
| vbQuestion
| 32
| Display Warning Query icon.
| vbExclamation
| 48
| Display Warning Message icon.
| vbInformation
| 64
| Display Information Message icon.
| vbDefaultButton1
| 0
| First button is default.
| vbDefaultButton2
| 256
| Second button is default.
| vbDefaultButton3
| 512
| Third button is default.
| vbDefaultButton4
| 768
| Fourth button is default.
| vbApplicationModal
| 0
| Application modal; the user must respond to the message box before continuing work in the current application.
| vbSystemModal
| 4096
| System modal; all applications are suspended until the user responds to the message box.
| vbMsgBoxHelpButton
| 16384
| Adds Help button to the message box
| VbMsgBoxSetForeground
| 65536
| Specifies the message box window as the foreground window
| vbMsgBoxRight
| 524288
| Text is right aligned
| vbMsgBoxRtlReading
| 1048576
| Specifies text should appear as right-to-left reading on Hebrew and Arabic systems
| |
---|
The first group of values (0–5) describes the number and type of buttons displayed in the dialog box;
the second group (16, 32, 48, 64) describes the icon style;
| the third group (0, 256, 512) determines which button is the default;
| and the fourth group (0, 4096) determines the modality of the message box.
| When adding numbers to create a final value for the buttons argument, use only one number from each group.
| |
---|
An Example:
Dim intAnswer as integer intAnswer = msgbox(“Are you sure”, vbYesNo + vbQuestion) If intAnswer = 7 then |
---|
Constant | Value
vbOK
| 1
| vbCancel
| 2
| vbAbort
| 3
| vbRetry
| 4
| vbIgnore
| 5
| vbYes
| 6
| vbNo
| 7
| |
---|
Programmer Defined Functions |
---|
lblAmount.Caption = FormatCurrency(sngAmount,0) sngAmount = Val(txtAmount.text) if IsNumeric(txtAmount.text) |
---|
Public Function FunctionName([arguments]) [As type] : : FunctionName = (some value) End Function |
---|
Public Function Square(ByVal intNum as Integer) as long ‘ return data type ‘To return a value you make the name of the function = the return value Square = intNum ^ 2 End Function |
---|
lngAnswer = Square(intNum) |
---|
Control Break Logic |
---|
Report summary information for the group just completed. If the key field value is to be used in the summary information you must use the value stored in the working variable.
| ||
---|---|---|
You might add any intermediate accumulators or counters to grand totals.
Reinitialize any accumulators or counters associated with the group
| Save new key field value in the working variable
| |
If blnFirstRecord = True then Save key field value in working variable Turn Boolean variable off End if |
---|