Uploaded by Nora Chamseddin

CP212 Final 1 .pdf

advertisement
CP212 Final
●
Chapter 1 - 4:
o VBE: IDE for programming with VBA in Excel
▪
o
Accessed by pressing Alt+F11
Excel Document Object Model
▪
Object Browser: Opens a ton of libraries you can get help on
●
o
o
Excel Library: Provides help on all objects and their properties and
methods in the Excel object model
● VBA Library: provides help on VBA elements that are common to all
applications that can use VBA (e.g. Excel, Access, Word)
● Office Library: provides help on objects common to all Office programs
(e.g. CommandBars objects)
Macros: Recording of a set of commands you perform that can play back again
Identifying parts of the VBE (especially debugging)
▪
Standard:
●
▪
Edit:
●
▪
Debug:
●
●
Chapter 5 o String Functions
▪
Right("Henderson", 3) returns "son"
▪
Left("Henderson", 4) returns "Hend"
▪
' Mid(String, start, [Length])
●
Mid("Henderson", 2, 5) returns "ender"
●
o
o
o
o
Mid("Haxxor", 3) returns "xxor”
o String indexes are based at 1
▪
theLength = Len("My Career") ' The length is 9
▪
Instr function: Checks if substring is anywhere inside given string and, if it is,
where it begins within the string
● E.g. Instr(1, “Albright, Christ”, “,”)
● 1 in the beginning indicates search should start in the beginning
Subroutine aka Subs: Logical section of code that performs a particular task
Creating Object Variables - Need to use the Set keyword
Constants - Need to use the Const keyword
3 Types of Errors
▪
Syntax errors
●
●
●
Occur when you:
o Spell something wrong
o Omit a keyword
o Commit various other “grammatical” error
Caught easily during coding because IDE tells you when you've types in a
command wrong
Code won't compile while you have Syntax errors
●
▪
Runtime errors
●
●
●
▪
Occur when something is wrong with your code, but the error is not
discovered until you run your program
o E.g. this will be out of bounds errors on an array index
Code you wrote is correct, but if your code tries to go past the correct
size of the array, it will stop and generate an error
To solve:
o Click the Debug button and the line of code that generated the
error is highlighted in yellow and displayed in the VBE
o Track down the problem to the exact problem which may
appear in earlier lines of code (like when a variable was assigned
the wrong value)
o In debug mode, often you'll be able to place your mouse over
variables and it will display their current value in a tooltip
Logic errors
●
●
●
Hardest to find because they don't cause a crash, only bad results
You don’t know what made the error
To solve:
o
o
●
Can use the step through feature, set breakpoints and include
"watches" - specify a variable to watch as its value changes so
you can find the problem
See text and lab material for more debugging info / demo
Chapter 6 o Range Objects
▪
o
Range: Represents cell, row, column, or selection of cells
Properties of a Range:
▪
Rows: Returns Range object that represent rows in specified range
●
●
E.g.
Worksheets("Sheet1").Range("B2:Z44").Rows(3).Delete
▪
Columns: Returns Range object that represents columns in specified range
▪
Offset: Returns Range object that represents range that's offset from specified
range
▪
Sort: Sorts a range of values
▪
Address: Returns the address of the range as a string like $C$2:$D$7
●
▪
This is absolute cell referencing
Cells: Access individual cells within a range by using an index of either just the
number of the cell within a range or a row and column (i.e. a rectangular array)
● E.g. Range("A1:A10").Cells(3) refers to the 3rd cell in the range, A3
▪
Font: Allows us to manipulate and customize the text (e.g. bold)
●
▪
Formula, FormulaR1C1
●
●
▪
E.g. Range("B15").Value = 17
Worksheet
●
●
E.g. Range("A3:A10").Name = "Sales"
Value: Returns of sets a Variant value that represents value of specified range
●
▪
FormulaR1C1 is useful when you need to copy-paste a formula
Formula in excel always has to start with an equal sign
Name: Returns or sets a Variant value that represents name of object
●
▪
E.g. Range("A2").Font.Bold = true
Worksheet object is a member of Worksheets and Sheets collection
Chapter 7 o Debugging Loops
o Logic Constructs (if, case)
▪
If-Then:
●
▪
Case:
●
●
●
o
●
Nested If or ElseIf statements becomes unmanageable around 3 test
cases - at that point use the Case constructor tool
Case construction used as less complex alternative to complex if
constructions
Syntax:
o
for-next, for-each, do while loop and varieties
Chapter 8 o Objects: Grouping of data and methods
o Workbook: Workbook object is a member of the Workbooks collection
o Worksheet: Worksheet object is a member of the Worksheets and Sheets collection
o Collections
▪
Workbooks Collection: Collection of all open workbooks
●
●
●
▪
Does not include Excel files on your hard drive not currently opened
Member of workbooks collection can be specified with its name
o E.g. Workbooks("Customer.xlsx")
Contains Worksheets collection and Charts collection
Worksheets Collection: Can be referred to by their code name
●
●
●
o
Advantages of using code name:
o If user changes tba name of worksheet, code name stays fixed
o You can refer directly to codename such as wsData with a line
like wsData.Range("A1"), you don't need to declare a worksheet
object and set it as shown below
Dim ws As Worksheet
Set ws = Worksheets("Data")
Charts
▪
Parts of a Chart
▪
●
●
●
●
●
●
●
●
●
●
A - Chart area
B - Title
C - Y-axis
D - X-axis aka Category Axis
E - Legend
F - Plot Area
G - Series
H - Y-axis Label
I - X-axis Label
Chapter 9 - Arrays
o Declaring Arrays
▪
▪
▪
o
Resizing Arrays
▪
▪
Preserve keeps values during resize
▪
o
Dynamic/Static Arrays
▪
Dynamic Arrays: Can be resized
▪
o
●
Static Arrays: Cannot be resized; will give error message
Clearing Arrays
▪
Use Erase keyword
▪
E.g. Erase arr
Chapter 10 o Scope (2 questions)
▪
3 Levels
●
●
●
o
o
o
●
Sub-Level aka Local: Variable declared inside sub, cannot be accessed
outside of sub
Module-Level: Variable declared outside of scope, every sub in module
can access variable, can be public or private
Project-Level:
o If public, all modules can access it
o If private or undeclared, can only be accessed in that module
Functions
IsDate(): Good for data validation, checks if date is valid
IsNumeric(): Good for data validation, checks if number is valid
Chapter 11 o Userforms: How to Display
o
▪
To display: Show userform
▪
To hide: Unload userform
Identify form controls
▪
▪
1 - Label
▪
2 - TextBox
▪
3 - Group Box
▪
4 - OptionButton
▪
5 - CheckBox
▪
6 - CommandButton
▪
▪
●
Chapter 12 - Error Handling: Turn it on, Turn it Off
o On: Application.DisplayAlerts = False
o Off: Application.DisplayAlerts = True
●
Chapter 13 - Working with Files
o The FileSystem Object
▪
FileSystemObject: Provides access to computer's file system
▪
Contains Drive, File, Folder and TextStream objects
●
Drive: a drive or collection of Drives
●
●
●
File: represents a file or collection of files
Folder: a folder or collection of folders
TextStream: represents a stream of text for a text file that
▪
Can be read from, written to or added to (appended)
▪
Use either early binding or late binding
●
o
o
Early Binding
o Need to reference Microsoft Scripting Runtime
● Late Binding
o Need to create instance of FSO object
Types of Dialog Boxes
▪
MsgBox: Display information to the user
▪
InputBox: Get information from the user
Reading Text Files (Using Channel #)
▪
Text files are delimited pieces of data
▪
o
TextStreams: Alternative but powerful way to write files
▪
●
Chapter 14 o Tables
o Database Basics
▪
Data retrieved using queries can be done in two ways
●
●
▪
QBE - Query By Example
SQL - Structured Query Language
Referential Integrity: When we pull data out of the database its gonna be correct
and won't have any flaws
▪
The common way to access a database from VBA - steps:
●
●
●
●
●
o
●
●
SQL Statements
▪
Create an ADO connection to a database
Open the database connection
Create an ADO recordset
Open the recordset
Extract the data you need from the recordset
o Usually using a loop to do so
Close the recordset
Close the connection
5 Key SQL Things:
●
●
●
SELECT: Lists data
FROM clause: Specifies the table(s) you want to pull data form
WHERE: Lists criteria to narrow down the data (filter)
o
●
●
▪
Basic Usage:
●
▪
SELECT fields FROM tables
Complete Usage:
●
●
i.e. If you want to only see Canadian customers you would use
the where clause
GROUP BY: Allows creation of subtotals - for grouping the data
according to value
o E.g. All critical
ORDER BY: Allows sorting orders (Ascending or Descending)
SELECT a FROM b WHERE c ORDER BY d
Chapters 15 (3Q) –
o What are Pivot tables?
▪
Pivot Table: Used to view and organize data, allow grouping of data in different
ways
▪
o
Data layout can be
● Categorical (e.g. Male/Female, yes/no, low/medium/high)
● Numerical (e.g. Dollar values, counts, number of catalogs)
Why automate Pivot tables?
▪
User won't have to remember to update it whenever source data has been
updated
●
Chapter 16 (3Q) - RibbonX
o RibbonX: Interface technology
o
o
o
Change Ribbon: File → Options → Customize Ribbon
Application-Level Changes: Availible regardless of which file is open
▪
o
o
●
Used to access commonly used features (e.g. Customer macro)
Limits
▪
Small amount of icons availible
▪
No other form controls
Solution - Do it yourself
Chapter 17 (5Q) –
o Solver code
▪
Solver: Finds optimal or min/max solutions to mathematical models
●
●
●
▪
Add-in for Excel designed to solve problems in linear programming
Can generate 3 reports:
o Answer
o Sensitivity
o Limits
Basic Steps:
o Reset Solver using SolverReset
o Define Target Cell using SolverOk
o Add Constraints using SolverAdd
o Set some options using SolverOptions
o Solve using SolverSolve
Model: Mathematical way to represent problem
●
Components
o Target Cell - the goal
o Changing Cells - going to be changed until they satisfy the
constraints
o Constraints
▪
▪
Solver Code
●
●
Defined by business logic
●
●
o
●
Note:
o 1 - Maximize
o 2 - Minimize
o 3 - Match a specific value
How to fix Solver if it won’t run
▪
Make sure Solver is enabled
▪
Try reinstalling solver
Chapter 18 o Classes
▪
Classes: Blueprints for objects
●
Contain encapsulation of data and methods that act on data
▪
Instantiation: Creating an instance of an object
▪
When creating a class, Add, Item, Remove, and Count are properties of the
Collection Object, so you don't have to write the code yourself
▪
Class Constructors: Sub that always runs when object is instantiated, named
Class_Initialize
● Good for setting initial values
● Not necessary for you to create
● Add, Item, Remove, and Count are properties of the Collection Object,
so you don't have to write the code yourself
▪
Class Operations:
●
●
●
o
Looping
Debugging
Counting
UDTs
▪
UDT: User Defined Type
▪
E.g.
●
▪
o
Declaring UDTs
●
Enumerations: Type that contains enumeration of constants
▪
Create list of items and makes them in a group
▪
E.g.
●
●
o
●
Now we can create variables called gender that have the value male or
female
Instantiating Objects
Office Automation o Early Binding
▪
o
Late Binding
▪
o
DIFFERENCE BETWEEN LATE VS. EARLY BINDING
▪
●
Variable declaration, i.e. Dim statement
Event Driven Programming
o Modern, graphical oriented programs are driven by events
o Program will be running in memory, waiting for user/system to do something
o Events: Things the user/system does
o Events and Even Handlers
▪
Typical events: clicking a button, moving the mouse, typing in text, etc.
▪
Event Handler: Code that, when an event happens, responds to that event and is
executed
▪
●
Event is said to have fired or been triggered
UX - User Experience
o UX: Subjective experience user has when performing task while using your software
(make them happy, not angry)
▪
Intersection of Art, Science, and Craftsmanship
Download