SlideShare a Scribd company logo
1 of 19
VBA Programming for Excel






Review Excel Objects
Excel Methods
Identifying Specific Cells
Review Functions for Excel
Custom Menus
Range Objects


Range(Name)





Name: text string
“B3”,”Input”

Offset



Range(“B3”).Offset(2,1) = Range(“C5”)
Offset numbers can be called
MyNumber = 3
Range(“D4”).Offset(myNumber, -1).Select
<Results: Cursor ends up in cell C7>
Default Objects


ActiveCell





ActiveSheet





ActiveCell.Offset(0,1).Select
RowNum = ActiveCell.Row
ActiveSheet.Name = “Data”
ActiveSheet.Visible = VeryHidden

Selection


Selection.Clear
What does this code do?
ActiveCell.Offset(Range(“B2”),-2) = [b4]/4

4
Controlling Objects




Use assignment statements to change
objects or properties
Different effects, similar results





Range(“F3”).Value = Range(“D3”).Value*15
Range (“F3”).Formula = “=D3*15”
First form enter a number – no updates!
Second form enters a formula
Collections


Worksheets





Worksheets(1)
Worksheets(“Sheet2”)

Columns

Columns(“C:D”).HorizontalAlignment = xlCenter



Rows

Rows(5).RowHeight = 19.5



Note difference between Row and
Rows
Excel Methods



Record macros to define
Copy, Paste
Range(“B3:D6”).Select
Selection.Copy



Sort
Find a Given Cell


GoTo







Edit, Goto, Special
Last Cell
Current Region

{End}{Down}
Find first column in the last row
Look-ups


VLookUp(value, table, col_num, close)



Value: item to find
Table: range of data to search





Must be sorted by 1st column

Col_num: which column has data?
Close: true or false



True: select nearest match – always finds
False: find exact, or return #N/A
VLookUp

True: find
closest match

Value to LookUp
Search range
Return column
Spreadsheet Functions in VBA


Application.WorkSheetFunction.Name(Arguments)
Application.WorksheetFunction.Today()



Cell addresses must appear as ranges
Application.WorkSheetFunction.IsNumber(Range(“B3”))




Most worksheet functions have a VBA equivalent
Functions must be used in assignment statements
vAns = Application.WorkSheetFunction. _
vLookup(Range(“A10”), Range(“A2:C8”), 3, True)
vOut = Range(“A10”).formula & “ lives in “ vAns
MsgBox vOut
Find()








VBA Function – not available on sheet
Expression.Find(What)
Expression must define a range on the
spreadsheet
Returns Range location of first match
Expression range need not be sorted
If no match is found, it returns Nothing
Find( ) Function
Range(“C10”).Value = _
Range(“A2:A8”).Find(“Gene”).Offset(0,2).Value
Looks in cells A2:A8 for
“Gene”,
returns [A5]
Offsets 2 cells right from [A5]
returns [C5]
Finds the value in [C5] = 58
Puts the value 58 in [C10]
User Defined Functions


You can write your own custom functions







Decide what information will be passed in
(Arguments)
Decide what value will be returned
Decide how VBA will use the arguments to
calculate the returned value
Example: Determine employee bunuses




Argument: Amount of sales
Return value: Bonus amount
Bonus = 2% if Sales > $50,000
User-defined Functions



Form: Function Name(Arguments)
Unlike Sub – the name of the function
must be repeated in the code
Function Bonus(Sales)
If Sales > 50000 Then
Bonus = Sales * 0.02
Else
Bonus = 0
End If
End Function
Using Custom Functions


Functions can be called from another sub
vSales = Range(“B3”).Value
vBonus = Bonus(vSales)
Range(“C3”).Value = vBonus



Functions can be used in the spreadsheet
Use Function Generator [fx]
 Look under “User-defined”
 Place cursor in [C3], write:
=Bonus(B3)





Note how the results differ!
See VBAFunctions.xls in the handouts
Custom Menus



Define Variables
Use Set to define contents
Dim myButton As CommandBarButton
Set myButton = CommandBars("Worksheet Menu Bar")_
.Controls("Tools").Controls.Add
With myButton
.Caption = "Say Hi"
Caption: Words in menu list
.MoveBefore:=4
MoveBefore: Position in list
.OnAction = "SayHi"
OnAction: Macro to call
.FaceId = 2174
FaceID: Icon to display
End With
Removing Menu Items



Search the existing buttons
Remove identified items
For Each Item In CommandBars("Worksheet Menu Bar")_
.Controls("Tools").Controls
If Item.Caption = "Say Hi" Then
Item.Delete
Exit For
End If
Next Item
Activating Custom Menus







Menu code goes in a macro
Macro must be run to make menu
appear or disappear
Use WorkBook_Open to add menues
Use WorkBook_BeforeClose to remove
See SayHi.xls in the handouts

More Related Content

What's hot

Geometria analitica con geogebra secme 22589
Geometria analitica con geogebra secme 22589Geometria analitica con geogebra secme 22589
Geometria analitica con geogebra secme 22589EmilioEscalanteHerna
 
Java Graphics
Java GraphicsJava Graphics
Java GraphicsShraddha
 
Matlab 1
Matlab 1Matlab 1
Matlab 1asguna
 
Using single row functions to customize output
Using single row functions to customize outputUsing single row functions to customize output
Using single row functions to customize outputSyed Zaid Irshad
 
Common Coding and Design mistakes (that really mess up performance)
Common Coding and Design mistakes (that really mess up performance)Common Coding and Design mistakes (that really mess up performance)
Common Coding and Design mistakes (that really mess up performance)Sage Computing Services
 
Functions oracle (pl/sql)
Functions oracle (pl/sql)Functions oracle (pl/sql)
Functions oracle (pl/sql)harman kaur
 
FLOW OF CONTROL-NESTED IFS IN PYTHON
FLOW OF CONTROL-NESTED IFS IN PYTHONFLOW OF CONTROL-NESTED IFS IN PYTHON
FLOW OF CONTROL-NESTED IFS IN PYTHONvikram mahendra
 
Cookbook Oracle SOA Business Rules
Cookbook Oracle SOA Business RulesCookbook Oracle SOA Business Rules
Cookbook Oracle SOA Business RulesEmiel Paasschens
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Finalmukesh24pandey
 
EAV Sytem- Magento EAV Model
EAV Sytem- Magento EAV ModelEAV Sytem- Magento EAV Model
EAV Sytem- Magento EAV ModelKhoa Truong Dinh
 
Implementation of EAV pattern for ActiveRecord models
Implementation of EAV pattern for ActiveRecord modelsImplementation of EAV pattern for ActiveRecord models
Implementation of EAV pattern for ActiveRecord modelsKostyantyn Stepanyuk
 
Arrays, Structures And Enums
Arrays, Structures And EnumsArrays, Structures And Enums
Arrays, Structures And EnumsBhushan Mulmule
 

What's hot (19)

Python Lecture 4
Python Lecture 4Python Lecture 4
Python Lecture 4
 
Geometria analitica con geogebra secme 22589
Geometria analitica con geogebra secme 22589Geometria analitica con geogebra secme 22589
Geometria analitica con geogebra secme 22589
 
Java Graphics
Java GraphicsJava Graphics
Java Graphics
 
Matlab 1
Matlab 1Matlab 1
Matlab 1
 
Using single row functions to customize output
Using single row functions to customize outputUsing single row functions to customize output
Using single row functions to customize output
 
Common Coding and Design mistakes (that really mess up performance)
Common Coding and Design mistakes (that really mess up performance)Common Coding and Design mistakes (that really mess up performance)
Common Coding and Design mistakes (that really mess up performance)
 
To excel or not?
To excel or not?To excel or not?
To excel or not?
 
Functions oracle (pl/sql)
Functions oracle (pl/sql)Functions oracle (pl/sql)
Functions oracle (pl/sql)
 
Les01
Les01Les01
Les01
 
7. basics
7. basics7. basics
7. basics
 
FLOW OF CONTROL-NESTED IFS IN PYTHON
FLOW OF CONTROL-NESTED IFS IN PYTHONFLOW OF CONTROL-NESTED IFS IN PYTHON
FLOW OF CONTROL-NESTED IFS IN PYTHON
 
Cookbook Oracle SOA Business Rules
Cookbook Oracle SOA Business RulesCookbook Oracle SOA Business Rules
Cookbook Oracle SOA Business Rules
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Final
 
Primitives
PrimitivesPrimitives
Primitives
 
EAV Sytem- Magento EAV Model
EAV Sytem- Magento EAV ModelEAV Sytem- Magento EAV Model
EAV Sytem- Magento EAV Model
 
Implementation of EAV pattern for ActiveRecord models
Implementation of EAV pattern for ActiveRecord modelsImplementation of EAV pattern for ActiveRecord models
Implementation of EAV pattern for ActiveRecord models
 
Excel tutorial
Excel tutorialExcel tutorial
Excel tutorial
 
Arrays, Structures And Enums
Arrays, Structures And EnumsArrays, Structures And Enums
Arrays, Structures And Enums
 
Input output
Input outputInput output
Input output
 

Similar to Excell vba

Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Asfand Hassan
 
Useful Excel Functions & Formula Used everywhere.pptx
Useful Excel Functions & Formula Used everywhere.pptxUseful Excel Functions & Formula Used everywhere.pptx
Useful Excel Functions & Formula Used everywhere.pptxvanshikatyagi74
 
Sales invoice VBA excel user-form
Sales invoice VBA excel user-formSales invoice VBA excel user-form
Sales invoice VBA excel user-formKaran Verma
 
6 Function Built In (Excel 2019 dn 365).pptx
6 Function Built In (Excel 2019 dn 365).pptx6 Function Built In (Excel 2019 dn 365).pptx
6 Function Built In (Excel 2019 dn 365).pptxPuworkUtara OnSlideshare
 
Excel formulas-manual
Excel formulas-manualExcel formulas-manual
Excel formulas-manualsrv1972
 
Excel Macros and VBA Demo.docx
Excel Macros and VBA Demo.docxExcel Macros and VBA Demo.docx
Excel Macros and VBA Demo.docxgunjangupta861854
 
Excel Macros and VBA Demo.docx
Excel Macros and VBA Demo.docxExcel Macros and VBA Demo.docx
Excel Macros and VBA Demo.docxgunjangupta861854
 
Mdx Basics
Mdx BasicsMdx Basics
Mdx BasicsALIPPHAR
 
Introduction To Oracle Sql
Introduction To Oracle SqlIntroduction To Oracle Sql
Introduction To Oracle SqlAhmed Yaseen
 
Pranavi verma-class-9-spreadsheet
Pranavi verma-class-9-spreadsheetPranavi verma-class-9-spreadsheet
Pranavi verma-class-9-spreadsheetPranaviVerma
 
Creating A User‑Defined Function In Excel Using Vba
Creating A User‑Defined Function In Excel Using VbaCreating A User‑Defined Function In Excel Using Vba
Creating A User‑Defined Function In Excel Using VbaChester Tugwell
 
OBIEE 12c Advanced Analytic Functions
OBIEE 12c Advanced Analytic FunctionsOBIEE 12c Advanced Analytic Functions
OBIEE 12c Advanced Analytic FunctionsMichael Perhats
 

Similar to Excell vba (20)

belajar VBA
belajar VBAbelajar VBA
belajar VBA
 
Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)
 
Useful Excel Functions & Formula Used everywhere.pptx
Useful Excel Functions & Formula Used everywhere.pptxUseful Excel Functions & Formula Used everywhere.pptx
Useful Excel Functions & Formula Used everywhere.pptx
 
Introduction to DAX Language
Introduction to DAX LanguageIntroduction to DAX Language
Introduction to DAX Language
 
Sales invoice VBA excel user-form
Sales invoice VBA excel user-formSales invoice VBA excel user-form
Sales invoice VBA excel user-form
 
6 Function Built In (Excel 2019 dn 365).pptx
6 Function Built In (Excel 2019 dn 365).pptx6 Function Built In (Excel 2019 dn 365).pptx
6 Function Built In (Excel 2019 dn 365).pptx
 
50 MS Excel Tips and Tricks
50 MS Excel Tips and Tricks 50 MS Excel Tips and Tricks
50 MS Excel Tips and Tricks
 
Excel formulas-manual
Excel formulas-manualExcel formulas-manual
Excel formulas-manual
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
 
Project advance itt
Project advance ittProject advance itt
Project advance itt
 
Excel Macros and VBA Demo.docx
Excel Macros and VBA Demo.docxExcel Macros and VBA Demo.docx
Excel Macros and VBA Demo.docx
 
Excel Macros and VBA Demo.docx
Excel Macros and VBA Demo.docxExcel Macros and VBA Demo.docx
Excel Macros and VBA Demo.docx
 
Mdx Basics
Mdx BasicsMdx Basics
Mdx Basics
 
MA3696 Lecture 9
MA3696 Lecture 9MA3696 Lecture 9
MA3696 Lecture 9
 
Introduction To Oracle Sql
Introduction To Oracle SqlIntroduction To Oracle Sql
Introduction To Oracle Sql
 
Microsoft Excel
Microsoft ExcelMicrosoft Excel
Microsoft Excel
 
Pranavi verma-class-9-spreadsheet
Pranavi verma-class-9-spreadsheetPranavi verma-class-9-spreadsheet
Pranavi verma-class-9-spreadsheet
 
C++ functions
C++ functionsC++ functions
C++ functions
 
Creating A User‑Defined Function In Excel Using Vba
Creating A User‑Defined Function In Excel Using VbaCreating A User‑Defined Function In Excel Using Vba
Creating A User‑Defined Function In Excel Using Vba
 
OBIEE 12c Advanced Analytic Functions
OBIEE 12c Advanced Analytic FunctionsOBIEE 12c Advanced Analytic Functions
OBIEE 12c Advanced Analytic Functions
 

Recently uploaded

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 

Recently uploaded (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 

Excell vba

  • 1. VBA Programming for Excel      Review Excel Objects Excel Methods Identifying Specific Cells Review Functions for Excel Custom Menus
  • 2. Range Objects  Range(Name)    Name: text string “B3”,”Input” Offset   Range(“B3”).Offset(2,1) = Range(“C5”) Offset numbers can be called MyNumber = 3 Range(“D4”).Offset(myNumber, -1).Select <Results: Cursor ends up in cell C7>
  • 3. Default Objects  ActiveCell    ActiveSheet    ActiveCell.Offset(0,1).Select RowNum = ActiveCell.Row ActiveSheet.Name = “Data” ActiveSheet.Visible = VeryHidden Selection  Selection.Clear
  • 4. What does this code do? ActiveCell.Offset(Range(“B2”),-2) = [b4]/4 4
  • 5. Controlling Objects   Use assignment statements to change objects or properties Different effects, similar results     Range(“F3”).Value = Range(“D3”).Value*15 Range (“F3”).Formula = “=D3*15” First form enter a number – no updates! Second form enters a formula
  • 7. Excel Methods   Record macros to define Copy, Paste Range(“B3:D6”).Select Selection.Copy  Sort
  • 8. Find a Given Cell  GoTo      Edit, Goto, Special Last Cell Current Region {End}{Down} Find first column in the last row
  • 9. Look-ups  VLookUp(value, table, col_num, close)   Value: item to find Table: range of data to search    Must be sorted by 1st column Col_num: which column has data? Close: true or false   True: select nearest match – always finds False: find exact, or return #N/A
  • 10. VLookUp True: find closest match Value to LookUp Search range Return column
  • 11. Spreadsheet Functions in VBA  Application.WorkSheetFunction.Name(Arguments) Application.WorksheetFunction.Today()  Cell addresses must appear as ranges Application.WorkSheetFunction.IsNumber(Range(“B3”))   Most worksheet functions have a VBA equivalent Functions must be used in assignment statements vAns = Application.WorkSheetFunction. _ vLookup(Range(“A10”), Range(“A2:C8”), 3, True) vOut = Range(“A10”).formula & “ lives in “ vAns MsgBox vOut
  • 12. Find()       VBA Function – not available on sheet Expression.Find(What) Expression must define a range on the spreadsheet Returns Range location of first match Expression range need not be sorted If no match is found, it returns Nothing
  • 13. Find( ) Function Range(“C10”).Value = _ Range(“A2:A8”).Find(“Gene”).Offset(0,2).Value Looks in cells A2:A8 for “Gene”, returns [A5] Offsets 2 cells right from [A5] returns [C5] Finds the value in [C5] = 58 Puts the value 58 in [C10]
  • 14. User Defined Functions  You can write your own custom functions     Decide what information will be passed in (Arguments) Decide what value will be returned Decide how VBA will use the arguments to calculate the returned value Example: Determine employee bunuses    Argument: Amount of sales Return value: Bonus amount Bonus = 2% if Sales > $50,000
  • 15. User-defined Functions   Form: Function Name(Arguments) Unlike Sub – the name of the function must be repeated in the code Function Bonus(Sales) If Sales > 50000 Then Bonus = Sales * 0.02 Else Bonus = 0 End If End Function
  • 16. Using Custom Functions  Functions can be called from another sub vSales = Range(“B3”).Value vBonus = Bonus(vSales) Range(“C3”).Value = vBonus  Functions can be used in the spreadsheet Use Function Generator [fx]  Look under “User-defined”  Place cursor in [C3], write: =Bonus(B3)    Note how the results differ! See VBAFunctions.xls in the handouts
  • 17. Custom Menus   Define Variables Use Set to define contents Dim myButton As CommandBarButton Set myButton = CommandBars("Worksheet Menu Bar")_ .Controls("Tools").Controls.Add With myButton .Caption = "Say Hi" Caption: Words in menu list .MoveBefore:=4 MoveBefore: Position in list .OnAction = "SayHi" OnAction: Macro to call .FaceId = 2174 FaceID: Icon to display End With
  • 18. Removing Menu Items   Search the existing buttons Remove identified items For Each Item In CommandBars("Worksheet Menu Bar")_ .Controls("Tools").Controls If Item.Caption = "Say Hi" Then Item.Delete Exit For End If Next Item
  • 19. Activating Custom Menus      Menu code goes in a macro Macro must be run to make menu appear or disappear Use WorkBook_Open to add menues Use WorkBook_BeforeClose to remove See SayHi.xls in the handouts