vba and macros - the eye · worksheets (“sheet1”) refer to the worksheet named “sheet1”....

42

Upload: others

Post on 15-Oct-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc
Page 2: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

VBAANDMACROS

VBAisamajordivisionofthestand-aloneVisualBasicprogramminglanguage.ItisintegratedintoMicrosoftOfficeapplications.ItisthemacrolanguageofMicrosoftOfficeSuite.Previouslyitwasknownasxlm.

HowtoaccessVBAinMS-Excel-

1. PressALT+F11.2. GoToDeveloperTab->ClickVisualBasicIcon.Seeimagebelow.

Everyorganizationintoday’sworldreliesuponvariouskindsofdatabasesforstorageofallkindsofdata.Dataisthebackboneineveryaspectofanorganization,beitmanagement,marketing,finance,planning,technicalandproductionservices,issues,environmentetc.ExcelcanbeusedasadatabaseorwecancallitaspreadsheetapplicationwhichmanipulatesthedatastoredinitorsomeotherdatabaselikeSQLServer,Oracledatabase,MySQLetc.Excelhasvariousfeatureslikeimplementingformulas,developingpivots,charts.ThemostimportantfeatureofexcelisthemacroprogramminglanguagecommonlyknownasVBAusedwithinexceltodevelopmacros.

VBAmeansvisualbasicforapplications.Officialnameis“VisualBasic,ApplicationsEdition.VBAisthevastestlanguageamongstallthehighlevellanguages.VBAisaneventdriven;objectorientedprogramminglanguagefromMicrosoftthatisnowprimarilyusedwithMicrosoftofficeapplicationssuchasMS-Excel,MS-WordandMS-PowerPoint.

SomefeaturesofVBAareasfollows–

1.)VBAisahighlevellanguagewhichanyoneknowingMSapplicationslikeexcelorwordcanlearn.Thislanguagehelpsincreatingamacrowhichisnothingbutaseriesofinstructionsforatasktobeperformedautomatically.

2.)VBAenablesusertoautomaterepetitivetaskssoastoreducethemanualeffort.

3.)VBAnotonlyoffersmacrostobecreatedbutalsoallowsusertocreateUDFsi.e.userdefinedfunctions.Thesefunctionsoncebuiltareincorporatedinthelibrarywithallotherexcelfunctions.

4.)VBAworksonwindowsmachinesoisplatformdependent.

5.)VBAhelpsineliminatingwasteandisbasedonagilemethodology.

6.)VBAisanOOPi.e.objectorientedlanguage.EverythinginVBAistreatedasanobject.

Page 3: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

7.)VBAcanbeusedtoconnecttoanydatabaseotherthanexcelitselflikeMySQL,Oracleetc.Itmakestheconnectionwiththebackenddatabaseandmanipulatesdataasrequired.

8.)VBAcanbeusedwithallMicrosoftapplicationslikeMS-Word,MS-Access,Outlook,MS-Powerpointetc.

9.)VBAmacrosareuserspecificandnotauthorspecific.Theycanbemodified,deletedbytheuserwhowantstorunit.

10.)VBAinMS-OfficeprovidesmanyinbuiltfunctionsthatausercanusetobuildcodeinExcel.

11.)VBAallowsuserstorecordthemacrosandthentweakthemforspecificpurposes.

12.)VBAisalsousedbydataanalysts,finance&marketanalystsfordatamanipulation,modelingetc.Mathematiciansuseitduetoitsvastlibraryfullofformulasandfunctions.

13.)VBAallowscodertoswitchoffcalculationsandsheetsupdateduringexecutionofcodewhichspeedsuptheprocessing.

14.)VBAisaSelf-interpretedprogramminglanguage.CompilingisveryeasyinVBA.

15.)VBAcanhelpbuiltPowerfultoolsinMSOfficeusinglogicalprogramming.

16.)ThereisafamousonelineraboutVBAthatthereisnothingwhichcan’tbedonebyVBA.

VBAEnablesend-userprogrammingandisusedinMSOfficeapplicationsastoldabove.ItencapsulatesFormulaeandmacrosforeasytasks.Followingarethecontentswhichwillbecoveredinthisbook–

1.)ConceptofVariablesandDataTypes.

2.)ConditionalandLogicaloperators.

3.)NestedLoops,SwitchCases,conditionalstatementsetc.

4.)ErrorHandling.

5.)Objecthandling.

6.)ConceptofsingleandmultipledimensionalarraysinVBA.

7.)Stringmanipulation.

8.)MacroRecording.

VBA–Collections

AGroupofSimilarObjectsthatShareCommonProperties,Methodsand

Page 4: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

EventsSuchasWorkbooks,Worksheets,etc.arecalledCollections.

WorksheetsareacollectionofalltheWorksheetobjectsintheactiveworkbook.

Worksheets(3)refertothe3rdworksheetofcurrentactiveworkbook.

Worksheets(“Sheet1”)refertotheworksheetnamed“Sheet1”.

VBA–Objects

VBAobjectsareWorksheet,Workbook,Range,Cell,Chart,Name,etc.

Worksheets(Sheet1)isanObjectReferringtotheFirstSheet

Range(“A1:A5”)isanObjectReferringtoaRangefromRow1,Column1toRow5,Column1

Range(“A1:B5”)isanObjectReferringtoaRangefromRow1,Column1toRow5,Column2.

Cells(1,1)orRange(“A1”)isanObjectReferringtoRange“A1”.Cells(2,1)orRange(“A2”)isanObjectReferringtoRange“A2”.

VBA–Properties,MethodsandEvents.

PropertiesarethePhysicalCharacteristicsofobjects–ForexampleWorksheets.Count,Worksheets.Visible=False,Range(“A1:B15”).Rows.Count,Range(“A1:A50”).Font.Bold=True.

MethodsaretheActionsthatCanbePerformedbyObjectsoronObjectsForExampleWorksheets.Save,Worksheets.Calculate,Range(“A1:A50”).ClearContents,ActiveCell.CopySpecial.

ObjectsCanRespondtoEvents,SuchasMouseClick,DoubleClickonaCell,ActiveaWorksheet,Open/Close/SaveaWorkbook,etc.

VBA–Macro

VBAMacrostartswith‘sub’keywordandendswith‘EndSub’Theformatisasfollows–

SubAny_Name()

‘YourCodehereinbetween

EndSub

VBAmacrocanbeassignedtoanyformcontrolforexampleabuttonoritcanbeexecutedindependentlyviasomecommandoptionassignedtoit.VBAmacrocanalsobeexecutedfromtheMacroswindowintheviewtabofthemenubar.

Page 5: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

OnceVBAcodeiswrittenintheexcelfileitshouldbesavedwith.xlsmextension.SomeVBAShortcutsareasfollows–

ALT+F11-ToviewVBAEditorALT+F8-TodisplayallmacrosALT+Q-TocloseVBAEditorandreturntoExcelF5-TorunaMacroF2-DisplayObjectBrowserF7-DisplaycodeeditorF1-DisplayhelpCtrl+G–ImmediateWindowF4–PropertieswindowCtrl+R–ProjectExplorer.

Seebelowfortheshortcutsdescribedabove.

GetStarted–

1.)EnableDeveloperTabFirst–GoToFileTab->

Page 6: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

2.)GoToOptions->AWindowwillappearlikethis->

3.)GoToCustomizeRibbonandcheckDeveloperTabasshownbelowandthenpressOK->

Page 7: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

4.)Developertabwillbeshownasbelowonyourexcelsheet.Thedevelopertabappearsonthemenubar.

BeforeCreatingyourfirstmacromakesuretodofollowingthings–

1.)PressALT+F11-VBAIDEwillgetopened.

2.)NowclickToolstabinthemenubaronthetopoftheIDE.SelectOptionsfromthedropdownasshownbelowinthesnapshot.

3.)Awindowwillappear.Justcheckwhetherthethingsshowninthesnapshotbelowarecheckedornot.

Page 8: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

LetUsWriteOurFirstVBACodebyinsertingFormcontrol.

1.)OnceyouhavedevelopertabonyourmenubarclickitandthengotoInsertinsidethedevelopertabandclickitasshownbelow.

2.)Formcontrolswindowappearsasshownabove,Nowclickonthe

Page 9: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

buttonandInsertasshownbelow.

3.)RightClicktheButton1andassignanewmacro.VBAIDEwillgetopened.WriteasimpleVBACodeisasfollows–

SubButton1_Click()

MsgBox“Hi,IhaveinsertedthismoduletowritemyfirstVBACode”

EndSub

4.)Seebelowforthecodeincodewindowandtheoutputinthemessageboxthatappears.

Page 10: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

HowtoaccessVBAEditorwithoutinsertingformcontrol–

1.)PressALT+F11inyourexcelfile.Awindowwillopenasshownbelow.

2.)NowInsertamoduleinitasshownbelow.Module1isthenameofthefirstmoduleinsertedasshownbelowwithredarrows.

3.)NowintheabovemodulewindowwriteapieceofVBAcodeasfollows.

Page 11: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

Subfirst_Program()

MsgBox“Hi,IhaveinsertedthismoduletowritemyfirstVBACode”

EndSub

Seebelowforthecodeincodewindowandtheoutputinthemessageboxthatappears.

TheCommentsinVBA

StatementsorsentencesinVBAcodestartingwithsinglequoteorREMkeywordisacomment.SeebelowinVBAIDE.

Page 12: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

TheConceptofVariables

ThefollowingaretheruleswhennamingthevariablesinExcelVBA-

Theymustnotexceed40charactersTheymustcontainonlyletters,numbersandunderscorecharactersNospacingisallowedItmustnotbeginwithanumberExamples–var1,my_varetc.

SeebelowinVBAIDE

DataTypes

1.)Numeric

2.)NonNumeric(String,Date,Boolean,Object,variant)

Declarationofvariables

1.)Implicit(Variableisinitializedandisvariantbydefault)

2.)Explicit(Example–DimvarasInteger)

ConditionalandLogicalOperators

1.)Conditional–(=,<,>,>=,<=,<>etc.)

2.)Logical(AND,OR,XORandNOT)

Page 13: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

ControlStructures

1.)IfthenElse

1. IfIndex=0ThenMsgBox‘HiZero’ElseIfIndex=1ThenMsgBox‘HiOne’ElseMsgBox‘HiNone’EndIf

2.)Switchcase

1. SelectCaseIndexCase0MsgBox‘HiZero’Case1MsgBox‘HiOne’CaseElseMsgBox‘HiNoneEndSelect

SeebelowinVBAIDE

LoopStructuresinVBA

1.)Theloopstructuresareusedwhenrepetitiveworkisbeingdone.

2.)Loopsmaketheexecutionsequentiallygiventhejump.Forexampleifaprocessisrequiredtoberun10timesthenweuse1to10.Ifaprocessisrequired

Page 14: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

tobedoneonlyoddtimesthenwefo1to10instepsof2.

3.)TherearevariouskindsofloopstatementsinVBA.

1. ForNextLoop2. WhileWendLoop3. Dowhileloop4. Etc

4.)SeebelowforcodeinIDE.

Displayingtableof5

Workingwithworksheets

1.)AsalreadyexplainedearliereverythinginVBAisanobjectforexampleworksheet,Range,Celletc.

2.)Worksheets(“Sheet1”).cells(1,2).valuereferstotheB1inSheet1ofexcelworkbook.

ErrorHandling–Followingarethewaysforit

1.)OnErrorGoToLineNumber(GoestothespecifiedlinenumberandCoderesumesfrom)

2.)OnErrorGoTo0(DisablesenablederrorhandlerinthecurrentprocedureandresetsittoNothing.)

3.)OnErrorGoTo-1(DisablesenabledexceptioninthecurrentprocedureandresetsittoNothing.)

4.)OnErrorresumeNext(Controlgoestothestatementimmediatelyafter

Page 15: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

theerroredstatement)

ArraysManipulationinVBA

1.)Arraysareasignificantpartofanyprogramminglanguagewhichactsasfrontendprocessingdatabase.

2.)UnlikevariablesArraysareusedtostoremultiplevaluesofsamedatatype.Arraysstorehomogeneousdata.

3.)Arraystoresthevaluesonthebasisofkeyvaluepairi.e.arrayindexesthevaluesstoresinit.TheLowerBoundandUpperboundcanbesetmanuallyforanarray.

4.)Ifyoutrytoaccessanyindexofthealreadybuiltarraythatdoesnotexistanerrornamed“SubscriptoutofRange”occurs.

5.)ArrayscanbeoftwotypeswhichareStaticandDynamic.Theformerisusedwhenthesizeofanarrayremainsthesamethroughoutintheprocedurewhilethelatterpermitstheusertoregulatethesizeofanarrayatruntime.

6.)MostlyinVBAsingledimensionalarrayisusedalthoughVBAprovidesthefunctionalityofmulti-dimensionalarrays.

7.)AusercanonlypassanarraytoaprocedureusingByReferenceandausercanreturnanarrayfromafunctionbutthearray,itisassignedto,mustnotbecurrentlyallocated.

8.)AnyworksheetinaworkbookhasdataintheformofRowsandcolumns.Sobasicallythedatastoredistwodimensional.Anydatafromexcelsheetcanbedirectlytransferredtoatwodimensionalarrayandviceversaformanipulationpurposes.

RecordingaVBAMacro

1.)Let’srecordamacro.

2.)Gotoexcelwhileyouareworkingon.ClickViewinmenubarandthenclickMacrosontheextremeright.Adropdownwillappear.ClickontheRecordMacrojustbelowViewMacros.Seebelow.

Page 16: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

3.)Nowonceyouhaveclickedtherecordmacro,whateveractivityyouwilldointhatexcelfilewillberecorded.

4.)TheMacrorecordingisusefulwhenyouaredoingsomerepetitivetaskonthedailybasis.

5.)TheMacrorecordedcanbetweakedfurtheraspertheuser’sneed.

AnExampleVBA

SubButton1_Click()

DimmyValueAsVariant

‘Displaying‘AMessage’

MsgBox“Hi!IamaVBAcoder”

‘Addingtwovalues

MsgBox2+3

‘Addingtwovaluesinworksheet

Worksheets(“Sheet1”).Cells(1,3)=Worksheets(“Sheet1”).Cells(1,1)+Worksheets(“Sheet1”).Cells(1,2)

‘InputBoxandAssigningvaluetoRangeA2

MyValue=InputBox(“Givemesomeinput”)

Range(“A2”)=MyValue

‘Copyandpasterange

Range(“A1:A2”).Select

Selection.Copy

Range(“L1”).Select

ActiveSheet.Paste

EndSub

Page 17: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

CodeinIDE–VBAWindow.

Outputisasfollows-

SAMPLEVBACODESFORYOURUSAGE–

1.)VBAcodeforsimplemathematicalcalculationsusingvaluesinworksheet’scells.Somecodelinesareasfollows–

Page 18: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

1. Worksheets(“Sheet1”).cells(1,1).value=9002. Worksheets(“Sheet1”).cells(1,1).value=1003. Worksheets(“Sheet1”).Cells(4,2).Value=Worksheets(“Sheet1”).Cells(1,

2).Value+Worksheets(“Sheet1”).Cells(2,2).Value4. Completecodeisshownbelowinthesnapshot.

Outputisasfollows–

2.)CheckingifaNumberenteredbytheuserisEvenorOdd.SeeCode–

Page 19: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

Output–

3.)CodeforSortingacolumn–

Output–

Page 20: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

4.)CodetosendamailfromExcelviaOutlook.Justpastethecodeasshowninthesnapshotbelowandchangeyourfieldsaccordingly.

Output–

Page 21: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

5.)ConcatenatingTwoStringsinVBA.Seecodebelow-

6.)SomeStringmanipulationFunctionsinVBA.Seecodeandoutputasshownbelow.

Page 22: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

7.)WorkingwithDocfile–

Page 23: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

8.)SheetManipulation.AddingnewSheet,Deletinganexistingsheet,renamingasheetandcleaningthewholesheetetc.

Page 24: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

9.)WorkingwithArraysSubArrays_Manipulation()

DimCombineArrayAsString

‘WorkingWithArrays,Storingvalues1to10intheArraynamedArray1

CombineArray=””

DimArray1(1To10)AsInteger

Fori=1To10

Array1(i)=i

CombineArray=CombineArray&CStr(Array1(i))&“,”

Page 25: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

Nexti

MsgBoxCombineArray

‘Storingtableofsay17inArray1

CombineArray=””

Fori=1To10

Array1(i)=17*i

CombineArray=CombineArray&CStr(Array1(i))&“,”

Nexti

MsgBoxCombineArray

‘DispalyingLowerBoundandUpperBoundofArray

MsgBoxLBound(Array1)

MsgBoxUBound(Array1)

‘Summingthearrayelements

DimsumArrayAsInteger

sumArray=0

Fori=1To10

sumArray=sumArray+Array1(i)

Nexti

MsgBoxsumArray

‘Erasingthecontentsofanarray

EraseArray1

‘WorkingwithTwodimesionalArray

DimArray2(1To5,1To5),counterAsInteger

counter=1

Fori=1To5

Forj=1To5

Array2(i,j)=counter

counter=counter+1

Nextj

Nexti

EndSub

CodeinVBAIDE

Page 26: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

Theabovecodedescribestwokindsofarrays.SingledimensionalandDoubledimensional.Itshowshowtoentervaluesinthesekindsofarrays,howtoaccesstheelementsofmulti-dimensionalarray,howtoperformoperationslikesum,sort,eraseetc.

10.)DisplayingNameofeachworksheetandusageofForEach.

Page 27: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

11.)Hidingasheet,copyandpasteintosamesheetandanothersheet.

12.)Removingduplicatesfromacolumninexcelworksheet.

Page 28: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

SeetheInputandOutputasshownbelow–

13.)HowtogenerateaRandomNumber?

Outputisasfollows–

14.)CreatingGraphUsingVBA.Seethecodebelow–

Let’sSaywehavethefollowingdata.Wewillmakeacodetorepresentthiswithagraph.

Page 29: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

Code-Bychangingthedesiredvaluesinthecodebelowyoucancreateagraphforanydata.

Output–

Page 30: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

15.)Createapatternusingnestedloops–Thecodebelowwillteachyouhowtousenestedloopsandcreatingpatternsofvariouskindsbyjustmanipulatingtheseloops.

Output–

16.)Creatingpivotbyrecordingandthentweakitasperyourrequirement.

Let’stakethesameolddata–

Page 31: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

RecordedcodeinVBA–

Output–

Page 32: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

17.)Codetoswapvaluespresentincells.

InputandOutputaftercodeexecution–

18.)VBAcodetodeletealldatafromthesheetandremovingthefiltersifthey

Page 33: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

exist.

InputSheetwithDataandfiltersapplied

Outputafterthecodeisexecuted–

Allthedatahasbeendeletedandfiltershavebeenremoved.

Page 34: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

19.)VBAcodetocreateanExamspreadsheetofstudentsandtheirgradesubmissions.

InputSheetcontainingstudentnamesandmarksobtainedinvarioussubjects.

GradeCriteria–

VBACodeforcalculations–

Page 35: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

Submarks_calculator()

Dimstudents(1To6)AsString

DimmaxmarksAsInteger

DimmarksobtainedAsLong

maxmarks=0

marksobtained=0

Fori=4To10

maxmarks=maxmarks+Worksheets(“Sheet1”).Cells(i,3).Value

Nexti

Worksheets(“Sheet1”).Cells(i,3).Value=maxmarks

Forj=1To6

Fori=4To10

marksobtained=marksobtained+Worksheets(“Sheet1”).Cells(i,j+3).Value

Nexti

Worksheets(“Sheet1”).Cells(i,j+3).Value=marksobtained

If((marksobtained*100)/maxmarks)<40Then

Worksheets(“Sheet1”).Cells(i+1,j+3).Value=“F”

EndIf

If((marksobtained*100)/maxmarks)>=40Then

Worksheets(“Sheet1”).Cells(i+1,j+3).Value=“E”

EndIf

If((marksobtained*100)/maxmarks)>=55Then

Worksheets(“Sheet1”).Cells(i+1,j+3).Value=“D”

EndIf

If((marksobtained*100)/maxmarks)>=70Then

Worksheets(“Sheet1”).Cells(i+1,j+3).Value=“C”

EndIf

If((marksobtained*100)/maxmarks)>=75Then

Worksheets(“Sheet1”).Cells(i+1,j+3).Value=“C+”

EndIf

If((marksobtained*100)/maxmarks)>=80Then

Worksheets(“Sheet1”).Cells(i+1,j+3).Value=“B”

Page 36: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

EndIf

If((marksobtained*100)/maxmarks)>=85Then

Worksheets(“Sheet1”).Cells(i+1,j+3).Value=“B+”

EndIf

If((marksobtained*100)/maxmarks)>=90Then

Worksheets(“Sheet1”).Cells(i+1,j+3).Value=“A”

EndIf

If((marksobtained*100)/maxmarks)>=95Then

Worksheets(“Sheet1”).Cells(i+1,j+3).Value=“A+”

EndIf

marksobtained=0

Nextj

EndSub

SnapshotofcodeinIDE

Page 37: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

SeeOutputinBoldRedbelow–

Page 38: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

20.)Generatingdifferenttypesofgraphfromagivendata.

Let’sseethedatafirst.LookBelowforthedataandthecontrolbuttonswhichwillshowdifferenttypesofgraphsonclicking.

CodeforGeneratingBarGraphisasfollows–

Page 39: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

Output–

CodeforGeneratingLineGraphisasfollows–

Outputisasfollows–

Page 40: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

CodeforChartTypeofGraph–

Outputisasfollows–

Page 41: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

21.)Codetodisplayfactorialofanumber.Subfact()

Dima,factAsInteger

a=InputBox(“Enteranynumberforitsfactorialcalculation”)

fact=a

Fori=a-1To1Step-1

fact=fact*i

Nexti

MsgBoxfact

EndSub

Page 42: VBA AND MACROS - The Eye · Worksheets (“Sheet1”) refer to the worksheet named “Sheet1”. VBA – Objects VBA objects are Worksheet, Workbook, Range, Cell, Chart, Name, etc

Output–