Topics Built-in functions commonly used in business applications String functions and formatting Dates and Times Formatting Data for output Error handling.

Slides:



Advertisements
Similar presentations
Computer Science & Engineering 2111 Text Functions 1CSE 2111 Lecture-Text Functions.
Advertisements

CPS120: Introduction to Computer Science INPUT/OUTPUT.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Programming in Visual Basic
Introduction to C Programming
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Input Validation Check the values entered into a text box before beginning any calculations Validation is a form of ‘self-protection’, rejecting bad data.
Computer Science 1620 Programming & Problem Solving.
Introduction to Python
CSI 101 Elements of Computing Spring 2009 Lecture #13 Programming in Visual Basic March 25 th – April 4 th, 2009.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
Introduction to C Programming
Entering Data in Excel. Entering numbers, text, a date, or a time n 1Click the cell where you want to enter data. n 2Type the data and press ENTER or.
Copyright © 2001 by Wiley. All rights reserved. Chapter 3: Variables, Assignment Statements, and Arithmetic Variables Assignment Statements Arithmetic.
BACS 287 Visual Basic String Manipulation. BACS 287 Visual Basic Strings In Visual Basic, a “string” is a series of text, numbers, and special characters.
Input/Output  Input/Output operations are performed using input/output functions  Common input/output functions are provided as part of C’s standard.
Computer Science 1000 Spreadsheets II Permission to redistribute these slides is strictly prohibited without permission.
Variables and Constants
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
Visual Basic: An Object Oriented Approach 5: Structured Programming.
1 Visual Basic for Applications (VBA) for Excel Prof. Yitzchak Rosenthal.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC BUILDING BLOCKS Bilal Munir Mughal 1 Chapter-5.
General Programming Introduction to Computing Science and Programming I.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
CSC 162 Visual Basic I Programming. Randomizing and Formatting Randomizing Formatting –User-Defined Formats –Named Numeric Formats.
The Java Programming Language
Input, Output, and Processing
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
CIS 338: Operators and Formatting in VB.NET Dr. Ralph D. Westfall April, 2011.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
Introduction to Exception Handling and Defensive Programming.
Input Textboxes Input Boxes Different than textboxes Good for small amount of input (form full of textboxes is not nice) X = Inputbox(“prompt message”,
Chapter 3: Formatted Input/Output Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
1 CS 106 Computing Fundamentals II Chapter 81 “Error Handling” Herbert G. Mayer, PSU CS status 6/14/2013 Initial content copied verbatim from CS 106 material.
EXPRESSION Transformation. Introduction ►Transformations help to transform the source data according to the requirements of target system and it ensures.
Conversion Functions.
Variables & Function Calls. Overview u Variables  Programmer Defined & Intrinsic  Data Types  Calculation issues u Using Functions  The val() function.
Chapter 4 Variables and constants. 4.1 Variables -Use of variables is good programming style -easier to modify -easier for a programmer to understand.
C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Chapter 3 – Examples The examples from chapter 3, combining the data types, variables, expressions, assignments, functions and methods with Windows controls.
Hungarian Notation A must in this course Every object used MUST be renamed including the form(s) using the following rules Form  frmFormName E.g. frmTemperature.
Programming with Microsoft Visual Basic th Edition
Chapter 4 Getting Started with VBA. Subroutines Subroutine is the logical section of code that performs a particular task. Subroutine is also called a.
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.
CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 5, Lecture 2 (Tuesday)
BACS 287 Programming Fundamentals 5. BACS 287 Programming Fundamentals This lecture introduces the following topics: – Procedures Built-in Functions User-defined.
Controlling Program Flow with Decision Structures.
JavaScript and Ajax (Control Structures) Week 4 Web site:
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
Chapter 3: Formatted Input/Output 1 Chapter 3 Formatted Input/Output.
Making Interactive Programs with Visual Basic .NET
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are used in programs so that values can be represented with.
© 2006 Lawrenceville Press Slide 1 Chapter 4 Variables  A variable is a name for a value stored in memory.  Variables are created using a declaration.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are created using a declaration statement. For example: Dim.
Introduction to Computing Science and Programming I
A variable is a name for a value stored in memory.
Topics Designing a Program Input, Processing, and Output
The Selection Structure
Chapter 2 part #3 C++ Input / Output
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
Coding Concepts (Data- Types)
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Chapter 2 part #3 C++ Input / Output
Chapter 1 c++ structure C++ Input / Output
Presentation transcript:

Topics Built-in functions commonly used in business applications String functions and formatting Dates and Times Formatting Data for output Error handling If time, listbox and reference edit controls Homework #10

String Functions Strings can be in length from 0 to 255 characters VBA-provided String functions Len(string) tells you the length of the string Len(“ABCDEF”) is 6 Chr(numeric expression) used to create a single character NewLine = Chr(13) The internal code for the “newline” character is 13. This converts the numeric value 13 into a character string value. When used in MsgBox, it causes output to begin on the next line in the output box.

String Functions 1 Removing blank or space characters Example: UserName = InputBox(“Enter your name:”) UserName = Trim(UserName) removes extra spaces from the beginning and end of the enter name. If the user had typed, Enter your name: John the extra spaces would be trimmed to convert “ John “ to just “John”

String Functions 2 Related string functions: LTRIM(string) removes extra spaces from the beginning or left-side of the string only. RTRIM(string) removes extra spaces from the end or right-side of the string only. TRIM(string) removes spaces from both sides

String Functions 3 Converting upper case and lower case text Example: InputValue = InputBox(“Select YES or NO:”) Select YES or NO: yes sets InputValue to “yes” To test the input value you could write, If InputValue = “yes” or InputValue=“YES” Then … Better approach: If UCase(InputValue) = “YES” Then...

String Functions 4 Similarly, you can convert all characters to lower case: InputValue = LCase(InputValue) would convert “YES” to “yes”, or “Yes” to “yes”.

String Functions 5 Extracting part of a character string S = “ABCDEFGHJIJKLMNOPQRSTUVWXYZ” Left ( S, 3) is “ABC” Right (S, 3) is “XYZ” Mid (S, 4, 3) is “DEF”

String Functions 6 Searching for one string inside another Instr() looks for pattern inside another string, and returns the position where it was found InStr(starting_position, SearchWithin, ForThis, Compare) The first and last parameters can be leftout, yielding the simpler InStr( SearchWithin, ForThis )

String Functions 7 S = “ABCDEFGHJIJKLMNOPQRSTUVWXYZ” InStr( S, “MNO” ) returns 13, since the “MNO” begins at the 13th character position in S. This function is often used together with LEFT() and RIGHT(). For example: UserName = “Bob Smith” BlankPosition = Instr( UserName, “ “) FirstName = Left (UserName, BlankPosition - 1) LastName = Right(UserName, Len(UserName) - BlankPosition)

String Functions 8 InStr’s first and last parameters StartingPosition indicates where the search should begin. The last parameter, Compare, can be 0 or 1. 0 means to find an exact match, while 1 means to ignore the case of the text (lower case treated same as upper case). The default is 0. Example: S=“The quick brown fox jumped over the lazy dog” Instr(S, “The”) returns 1 but Instr(4, S, “The”) returns 0 because “The” does not match “the” at the end of the sentence.

String Functions 9 Example: S=“The quick brown fox jumped over the lazy dog” Instr(S, “The”) returns 1 but Instr(4, S, “The”) returns 0 because “The” does not match “the” at the end of the sentence. Instead, probably want to use Instr(4, S, “The”, 1) which returns 33, since it ignores the case in the pattern match.

Dates Reference the Date keyword or the Time keyword to get current date and time Examples: Dim S as String S = Date MsgBox S displays 11/29/01 Dim MyTime, MyDate, MyStr MyTime = #17:04:23# MyDate = #January 27, 1993#

Time Example: Dim S as String S = Time MsgBox S displays 2:29:53 PM

Formatting Data 1 Formatting numbers, dates and time for program output Examples: You want currency values to display as “$43.00” You want the date to display as “Wednesday, 11/28/01” You want the time to display as “01:20:30 AM” The easiest way to format output is to use the Format() function Format(numeric expression, format selection) format selection can be VBA standard formats, or, can be a custom, user defined format.

Formatting Data 2 Some examples to illustrate the idea: s = Format( , "$#.##") produces “$ ”, always with two decimal digits. s = Format( , "$#,#.##") says to insert “,” between the 1000s digits, producing “$4,353.14”.

Standard Formats “General Number”Display number with no thousand separator. “Currency”Display number with thousand separator, if appropriate; display two digits to the right of the decimal separator. “Fixed”Display at least one digit to the left and two digits to the right of the decimal separator. “Standard”Display number with thousand separator, 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. “Long Date”System date format, “Wednesday, 11/28/01” “Long Time”System time format

Standard Format Examples Format (13) is just 13 (no formatting) Format ( , “Currency”) is “$4,361.45” Format ( , “Standard”) is 34,545, Format (.05, “Percent”) is 5.00% Format ( 0, “True/False”) is False Format ( 1, “True/False”) is True; non-zero is true Format ( 0, “Yes/No”) is No Format ( 35, “Yes/No”) is Yes; any non-zero is yes

Custom Format Examples ' User-defined formats. MyStr = Format( , “#.#”) rounds to MyStr = Format(5459.4, "##,##0.00")' Returns "5,459.40". MyStr = Format(334.9, "###0.00")' Returns "334.90". MyStr = Format(5, "0.00%")' Returns "500.00%". ‘ Case conversion built-in to the Format() function MyStr = Format("HELLO", "<")' Returns "hello". MyStr = Format("This is it", ">")' Returns "THIS IS IT".

Date Format Examples ' Returns current system date in the system-defined long date format. MyStr = Format(Date, "Long Date") ‘ Wednesday, 11/28/01 MyStr = Format(Date, “dddd dd mmm yyyy”) Wednesday 28 Nov 2001 mm returns the month number (e.g. 11) mmm returns a 3 letter abbreviation (e.g Nov) mmmm returns the entire month name (e.g. November) dd returns the day as a 2 digit number ddd returns the day as the day of the week (e.g. Wed) dddd returns the day as the day of the week (e.g. Wednesday) yy is the last two digits of the year yyyy is the full 4 digits of the year

Time Format Examples MyStr = Format(MyTime, "h:m:s")' Returns "17:4:23". MyStr = Format(MyTime, "hh:mm:ss AMPM") ' Returns "05:04:23 PM". S = Format(Time, "hh:mm:ss mm/dd/yy") Surprisingly, the Time object contains both date and time S is set to “11:20:35 11/29/01”

A Round() function Excel’s built-in Round() function is not accessible from VBA Function Round(x As Single, NumDigits As Integer) Round = Int(x * (10 ^ NumDigits)) / (10 ^ NumDigits) End Function How this works: Let x = , and NumDigits = 2 10^2 = 100 so this expression becomes * 100) which is int( ) is the integer part, or Then that is divided by 100 to convert back to decimal form, / 100 is

Handling Error Conditions Examples: Incorrect input from the user Error detected (or not detected) inside a subroutine Incorrect (or non-existent) initialization Random program performance Introduction to types of program errors How to handle error conditions in your program

Types of program errors Two Basic Program Errors: Syntax error - you wrote a program statement that VBA cannot process and VBA gives you a “compile” error Run-time error - something goes wrong while the program is running. You see a dialog box telling you about the error and offering to End or Debug the program.

Types of Errors Runtime error types: Input/Output faults (incorrect user input) Logic faults (error when writing the program) Computation faults (wrong algorithm, divide by zero) Interface faults (incompatible types, e.g. int=long) Data faults (failure to initialize, off by one errors)

Handling Input/output errors Runtime error “trapping” - catches the error and lets your program code handle the problem rather than crashing the program and displaying a rude dialog box. Dim X As Single X = InputBox("Enter a number:")

Here is what happens When you click Okay without entering a number:

Solutions #1:Dim S As String, X as Single S = InputBox(“Enter a number:”) If Len(S) <> 0 Then X = S End if ‘ But what if S contains text? #2:‘ Better way On Error Resume Next X = InputBox(“Enter a number:”) MsgBox “You entered: “ & X

Using the Err variable Dim X as Single On Error Resume Next X = InputBox("Enter a number:") If Err = 0 Then MsgBox "You entered: " & X Else MsgBox "Data entry error" End If Err is a VBA built-in variable that contains a code number indicating the most recent error condition. If Err is zero, then no error was detected. If Err is not zero, then an error occurred.

Writing an “Error Handler” Sub DemoError() On Error Goto Handler X = InputBox (“Enter a number:”) Exit Sub Handler: MsgBox (“You must enter a numeric value”) Resume ‘ back at statement that caused error End Sub

Disabling an Error Handler On Error Goto Handler remains in effect for rest of the subroutine To turn off error handling, use On Error Goto 0 Now, the program will crash if an error is encountered.

Looking Up an Error Code A generic but not necessarily user friendly error routine: On Error Goto Handler … code goes here … exit sub Handler: MsgBox "Error #=" & Err & ", " & Err.Description Resume End Sub

Error handling options in VBA

Logic faults Mistyping a variable name: use option explicit Practice_Variable = Practice_Varable + 1 Leaving out a Case in Select Case (e.g. “A”, “B”, “C”, “E”, “F”… omitting case “D”) Common mistakes: Using < instead of <= Using <= when you really meant <, etc.

Computation faults Your code implements the solution wrong You used the wrong method (algorithm) to solve the problem Omit or use parenthesis incorrectly: 3+5*8 when you wanted (3+5)*8 Round off, data truncation problems Example: copying a single ( ) to an Integer Dim X as Single, I as Integer X = I = X‘ Becomes 3, and you’ve lost the precision of X

Data faults Incorrect initialization: VBA is nice in that it sets all numeric variables to zero, and strings to “”. However, sometimes your code may be expecting a different initial value - and you forgot to initialize the variable. “off by one” - many of you saw this in problem #9 defined as 0 to 99, but tried to reference (100) Or defined 1 to 100, but tried to reference PracticeArray(101) Divide By Zero

Homework #10 See Homework10.doc on the class web site. Will prompt the user to input a full name and city name, and then use the string functions to break apart the input string and write the individual components in to the spreadsheet so that you end up with a table that looks similar to: