topics built-in functions commonly used in business applications string functions and formatting...

36
Topics uilt-in functions commonly used in business applica •String functions and formatting •Dates and Times •Formatting Data for output rror handling time, listbox and reference edit controls omework #10

Upload: anne-morton

Post on 26-Dec-2015

218 views

Category:

Documents


0 download

TRANSCRIPT

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

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

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

String Functions

Strings can be in length from 0 to 255 characters

VBA-provided String functionsLen(string) tells you the length of the stringLen(“ABCDEF”) is 6

Chr(numeric expression) used to create a single characterNewLine = Chr(13)The internal code for the “newline” character is 13. Thisconverts the numeric value 13 into a character string value.When used in MsgBox, it causes output to begin on the nextline in the output box.

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

String Functions 1

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

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

String Functions 2

Related string functions:

LTRIM(string) removes extra spaces from the beginningor left-side of the string only.

RTRIM(string) removes extra spaces from the end orright-side of the string only.

TRIM(string) removes spaces from both sides

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

String Functions 3Converting upper case and lower case text

Example:InputValue = InputBox(“Select YES or NO:”) Select YES or NO: yessets 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 ...

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

String Functions 4

Similarly, you can convert all characters to lower case:

InputValue = LCase(InputValue)

would convert “YES” to “yes”, or “Yes” to “yes”.

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

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”

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

String Functions 6

Searching for one string inside another

Instr() looks for pattern inside another string, and returnsthe 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 )

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

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)

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

String Functions 8InStr’s first and last parametersStartingPosition indicates where the search should begin.The last parameter, Compare, can be 0 or 1. 0 means tofind an exact match, while 1 means to ignore the case ofthe 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 1but Instr(4, S, “The”) returns 0 because “The” does notmatch “the” at the end of the sentence.

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

String Functions 9Example: S=“The quick brown fox jumped over the lazy dog” Instr(S, “The”) returns 1but Instr(4, S, “The”) returns 0 because “The” does notmatch “the” at the end of the sentence.

Instead, probably want to use Instr(4, S, “The”, 1) which returns 33, since it ignoresthe case in the pattern match.

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

Dates

Reference the Date keyword or the Time keyword to getcurrent date and time

Examples: Dim S as String S = Date MsgBox S

displays 11/29/01

Dim MyTime, MyDate, MyStrMyTime = #17:04:23#MyDate = #January 27, 1993#

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

Time

Example: Dim S as String S = Time MsgBox S

displays 2:29:53 PM

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

Formatting Data 1

Formatting numbers, dates and time for program outputExamples:

•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() functionFormat(numeric expression, format selection)

format selection can be VBA standard formats,or, can be a custom, user defined format.

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

Formatting Data 2Some examples to illustrate the idea:

s = Format(4363.14159, "$#.##")produces “$4353.14”, always with two decimal digits.

s = Format(4363.14159, "$#,#.##")says to insert “,” between the 1000s digits, producing“$4,353.14”.

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

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

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

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

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

Custom Format Examples

' User-defined formats.MyStr = Format(4635.784556, “#.#”) rounds to 4635.8MyStr = 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() functionMyStr = Format("HELLO", "<") ' Returns "hello".MyStr = Format("This is it", ">") ' Returns "THIS IS IT".

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

Date Format Examples' Returns current system date in the system-defined long date format.MyStr = Format(Date, "Long Date") ‘ Wednesday, 11/28/01MyStr = Format(Date, “dddd dd mmm yyyy”)

Wednesday 28 Nov 2001mm 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 numberddd 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 yearyyyy is the full 4 digits of the year

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

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 timeS is set to “11:20:35 11/29/01”

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

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 = 123.4567, and NumDigits = 210^2 = 100 so this expression becomes123.4567 * 100) which is 12345.67int(12345.67) is the integer part, or 12345Then that is divided by 100 to convert back to decimal form,12345 / 100 is 123.45

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

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

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

Types of program errors

Two Basic Program Errors:

Syntax error - you wrote a program statement that VBAcannot process and VBA gives you a “compile” error

Run-time error - something goes wrong while the programis running. You see a dialog box telling you about theerror and offering to End or Debug the program.

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

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)

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

Handling Input/output errors

Runtime error “trapping” - catches the error and letsyour program code handle the problem rather than crashing the program and displaying a rude dialog box.

Dim X As SingleX = InputBox("Enter a number:")

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

Here is what happensWhen you click Okay without entering a number:

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

Solutions

#1: Dim S As String, X as Single S = InputBox(“Enter a number:”)

If Len(S) <> 0 ThenX = S

End if ‘ But what if S contains text?#2: ‘ Better way

On Error Resume NextX = InputBox(“Enter a number:”)MsgBox “You entered: “ & X

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

Using the Err variable

Dim X as SingleOn Error Resume NextX = InputBox("Enter a number:")If Err = 0 Then MsgBox "You entered: " & XElse MsgBox "Data entry error"End If

Err is a VBA built-in variable that contains a codenumber indicating the most recent error condition.If Err is zero, then no error was detected.If Err is not zero, then an error occurred.

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

Writing an “Error Handler”

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

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

Disabling an Error Handler

On Error Goto Handlerremains in effect for rest of the subroutine

To turn off error handling, useOn Error Goto 0

Now, the program will crash if an error is encountered.

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

Looking Up an Error CodeA generic but not necessarily user friendly errorroutine:

On Error Goto Handler… code goes here … exit sub

Handler: MsgBox "Error #=" & Err & ", " & Err.Description ResumeEnd Sub

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

Error handling options in VBA

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

Logic faults

Mistyping a variable name: use option explicitPractice_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.

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

Computation faults

Your code implements the solution wrongYou used the wrong method (algorithm) to solve the problemOmit or use parenthesis incorrectly:

3+5*8 when you wanted

(3+5)*8

Round off, data truncation problemsExample: copying a single (3.14159) to an IntegerDim X as Single, I as IntegerX = 3.14159I = X ‘ Becomes 3, and you’ve lost the precision of X

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

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 differentinitial value - and you forgot to initialize the variable.

“off by one” - many of you saw this in problem #9defined as 0 to 99, but tried to reference (100)Or defined 1 to 100, but tried to reference PracticeArray(101)

Divide By Zero

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

Homework #10

First name Last name City Time DateBob Smith SPOKANE 11:29:01 Wednesday, Nov 14, 2001Lori Jones CHENEY 11:29:55 Wedneseday, Nov 14, 2001Tasha Pavlov DEER PARK 11:30:25 Wednesday, Nov 14, 2001

See Homework10.doc on the class web site. Will prompt the user to input a full name and city name, andthen 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: