Professional Documents
Culture Documents
Inthistutorialyouwilllearnthedifferencesbetweenafixedsizeanddynamicarray,howtoproperlydeclareeachone,howtoaccessthem,
howtoloopthroughthem,howtoerasethem,andafewotherthings.ThistutorialappliestoallversionsofVisualBasic,however,versions
beforeVisualBasic6.0donotincludethesplitandjoinfunction.Belowisalistofthemajortopicsthatwillbediscussed.
TypesofArrays
FixedSizeArrays
DynamicArrays
RetrievingtheContentsofanArray
AddingNewElementsontheFly
ErasinganArray
TheSplitFunction
TheJoinFunction
MultidimensionalArrays
Ifyouaren'tabletofindwhatyouneedhere,youcancheckoutthemainprogrammingsection(http://patorjk.com/blog/programming/)for
additionalVBcodeandtutorials.
Types of Arrays
AnarrayisalotlikeaCDrack.Youknow:oneofthoserectangularboxeswithslotstoslideCDsin,eachaboveanother.Therearetwotypesof
VisualBasicarrays:fixedsizeanddynamic.
Fixed-Size Arrays
AfixedsizearraymostcloselymatchesourCDrackanology.TherearealimitednumberofslotsyoucanslideCDsinto.Pretendyouhavethree
CDsonebytheDeftones,anotherbyTool,andathirdbyDisturbed.Tofitalloftheseinyourrack,therackmustcontainatleastthreeslots.
SoyoudeclareyourCDrackashavingthreeslots:
http://patorjk.com/programming/tutorials/vbarrays.htm 1/10
2/10/2017 VisualBasicArraysTutorial
You'vejustmadeavariable'strCDRack'thatcontainsthreeslots(#0,#1,and#2)andisofaStringdatatype.NowyoucaninsertyourCDsinto
it:
strCDRack(0) = "Deftones"
strCDRack(1) = "Tool"
strCDRack(2) = "Disturbed"
Noticethateachofthethreenewlinesstartsoffwiththevariablenameandthengivesanelementnumberbeforehavingavalueassigned.This
islikenumberingtheslotsonyourCDrackstartingat0upto2andtheninsertingaCDintoeachslot.Theformatfordeclaringanarrayis:
Dim|Public|PrivateArrayName(Subscript)AsDataType
Dynamic Arrays
ThenewCharlotteChurchCDcameoutbutyourrackonlyhasthreeslots.Youdon'twanttothrowawayanyofyourCDstomakeroomforthe
newonesoyoudecidetouseyourultimatebuildingskillstoattachanotherslot.Youstartbuilding:
strCDRack(0) = "Deftones"
strCDRack(1) = "Tool"
strCDRack(2) = "Disturbed"
Whathaveyoudone?Nothingwrong,you'vejustdimensionedyourarrayanotherwaythatallowsforexpansion.Noticethatthesubscriptof
the Dim statementismissing.ThisisOKittellsVBthatyourarrayisadynamicarray,meaningthatyoucanchangeitssizewith ReDim .
http://patorjk.com/programming/tutorials/vbarrays.htm 2/10
2/10/2017 VisualBasicArraysTutorial
Nowthatyou'verebuiltthestructureofyourCDrack,allowingforexpansion,itistimetoexpand:
strCDRack(0) = "Deftones"
strCDRack(1) = "Tool"
strCDRack(2) = "Disturbed"
Thissnippethastwomorelines,thefirstredimensioningthearrayoneelementlargerandthesecondsettingthiselement'svalue.Noticethe
Preserve keyword:itforcesVisualBasictoretainallexistingelements'values.WithoutthiskeywordallyouroldCDswouldbelostandyou'd
bestuckwithjustCharlotteChurch.
TheReDimkeyword'ssyntaxis:
ReDim[Preserve]ArrayName(Subscript)AsDataType
ReDim isthekeywordthatdenotesweareredimensioninganarray.
Preserve isanoptionalkeywordthatforcesVisualBasictoretainallexistingelements'values.Withoutitallelementswillreturntotheir
defaultvalues.(Numericdatatypesto0,variablelengthstringsto""(azerolengthstring),fixedlengthstringsfilledwithzeros,and
variantstoempty.)
ArrayNameisthenameofthearray.
Subscriptisthedimensionsofthearray.
DataTypeisanyvaliddatatype.Thedatatypecannotbechangedfromitsinitialdeclarationwhenusingthe ReDim keyword.(Unlessit
wasinitiallydeclaredasaVariant.)
http://patorjk.com/programming/tutorials/vbarrays.htm 3/10
2/10/2017 VisualBasicArraysTutorial
strFriends(0) = "Bianca"
strFriends(1) = "Jeana"
strFriends(2) = "Sam"
strFriends(3) = "Jenna"
strFriends(4) = "Erin"
strFriends(5) = "Carolyn"
strFriends(6) = "Kate"
That'sallgoodanddandybutyouwanttodisplaytheirnamesinsuccessivemessageboxes,soyouconstructaloop:
strFriends(0) = "Bianca"
strFriends(1) = "Jeana"
strFriends(2) = "Sam"
strFriends(3) = "Jenna"
strFriends(4) = "Erin"
strFriends(5) = "Carolyn"
strFriends(6) = "Kate"
MsgBox strFriends(lngPosition)
Next lngPositionlngPositionlngPosition
http://patorjk.com/programming/tutorials/vbarrays.htm 4/10
2/10/2017 VisualBasicArraysTutorial
Do
'Yes, so extend the array one element large than its current upper bound.
'Without the "Preserve" keyword below, the previous elements in our array
'would be erased with the resizing
ReDim Preserve strSongNames(0 To UBound(strSongNames) + 1) As String
Else
End If
End If
MsgBox strSongNames(lngPosition)
Next lngPosition
'Erase array
http://patorjk.com/programming/tutorials/vbarrays.htm 5/10
2/10/2017 VisualBasicArraysTutorial
Erase strSongName
Looktothecommentsforanexplanationofwhatisgoingon.
Erasing an Array
Youshouldalwayseraseyourarraywhenyouaredoneusingit,especiallyifyouareusingdynamicarrays.It'srathereasy:
strFriends(0) = "Bianca"
strFriends(1) = "Jeana"
strFriends(2) = "Erin"
Erase strFriends
It'dbeniceifwecouldeasilytakethatlistandputitinanarray,wouldn'tit?ThiscouldbedonebyusingVisualBasic'sbuiltinstringfunctions,
however,writingandupdatingthatcodecouldprovetobetimeconsumingandtedious.Luckilyforus,VisualBasic6.0providesabuiltin
functioncalled split thatallowsustoeasilyparseoutinformationfromastringandplaceitintoanarray.Ithasthefollowingsyntax:
ArrayName=split(StingInput[,Delimiter[,LengthLimit[,CompareMode]]])
StringInputisthestringthatyouwanttoparse.
Delimiterisanoptionalparameterthatindicateswhattypeofstringseparatestheelementsintheinputstring.Bydefaultthisparameter
issetto"".Thatwouldmeananinputstringof"Thisisatest"wouldyieldanarrayof4elements("This","is","a","test").
LengthLimitisthemaximumsizeyouroutputarraycanbe.Thetextremainingtobeparsedwillbesetasthefinalelementinthearray.
CompareMode.Bydefault,VisualBasiccomparesstringscharacterbycharacterusingtheirASCIIvalues.However,youcanusedifferent
modesthatwillcauseVisualBasictocomparestringsdifferently.Forexample, vbTextCompare causesstringcomparisonstobecase
insensitive.Thisparametereffectshowthe Delimiter parses InputString .
http://patorjk.com/programming/tutorials/vbarrays.htm 6/10
2/10/2017 VisualBasicArraysTutorial
Thefollowingisanexampleshowinghowtoparsethelistweshowedearlier:
MsgBox strCDRack(i)
Next
StringName=join(ArrayInput[,Delimiter])
ArrayInputisthearraythatyouwanttoplaceintoastring.
Delimiterisanoptionalparameterthatindicateswhatyouwanttoplacebetweenelementsareaddedtothestring.Bydefaultthis
parameterissetto"".
Usingoneofourpreviousexamples,hereissomesamplecodeonhowonemightusejoin:
http://patorjk.com/programming/tutorials/vbarrays.htm 7/10
2/10/2017 VisualBasicArraysTutorial
strFriends(0) = "Bianca"
strFriends(1) = "Jeana"
strFriends(2) = "Sam"
strFriends(3) = "Jenna"
strFriends(4) = "Erin"
strFriends(5) = "Carolyn"
strFriends(6) = "Kate"
'This will produce the following string: "Bianca, Jeana, Sam, Jenna, Erin, Carolyn, Kate"
myFriends = Join(strFriends, ", ")
MsgBox myFriends
Multidimensional Arrays
Sofaralloftheexampleswe'velookedathaveusedonedimensionalarrays,butarrayscanbemultidimensionaltoo.Multidimensionalarrays
canbethoughtofasarraysofarrays.Forexample,tovisualizeatwodimensionalarraywecouldpicturearowofCDracks.Tomakethings
easier,wecanimaginethateachCDrackcouldbeforadifferentartist.LiketheCDs,therackswouldbeidentifiablebynumber.Belowwe'll
defineatwodimensionalarrayrepresentingarowofCDracks.Thestringsinsideofthearraywillrepresentalbumtitles.
' Here we will define an array where the first dimension contains 2 elements and
' the second dimension contains 4 elements
ReDim cdRack(0 to 1, 0 to 3) As String
ThefirstitemofthefirstdimensionisanarrayforBeatlesCDswhiletheseconditemofthefirstdimensionisanarrayforRollingStonesCDs.
Youcouldalsoaddathirddimensionifyouwanted.KeepingwithourCDrackanalogy,youcouldpicturethisthirddimensionasahallwaywith
severalrooms.InsideofeachroomwouldbearowofCDsracks.Ifyouwantedyourhallwaystohave10rooms,eachwithCDrackslikethe
http://patorjk.com/programming/tutorials/vbarrays.htm 8/10
2/10/2017 VisualBasicArraysTutorial
onesintheaboveexample,youcoulddeclareyourarrayasfollows:
InVisualBasic6.0,youcancreatearrayswithupto60dimensions.InVisualBasic.NET,themaximumnumberofdimensionsanarraycan
haveis32.Mostarraysyouwillneedtodealwithwillonlybeoneortwodimensions.Multidimensionalarrayscanrequireadecentamountof
memory,sousethemwithcare,especiallylargemultidimensionalarrays.
Lastly,formultidimensionalarraysitshouldbenotedthatonlythelastdimensioncanberesized.Thatmeansthatgivenourexampleabove,
oncewecreatedthearraywithtwoCDracks,wewouldnotbeabletoaddmoreracks,wewouldonlybeabletochangethenumberofCDseach
rackheld.Example:
' Here we will define an array where the first dimension contains 2 elements and
' the second dimension contains 4 elements
ReDim cdRack(0 to 1, 0 to 3) As String
AwordfromPat(ownerofpatorjk.com):Ihopeyou'veenjoyedandlearnedsomethingfromthistutorial.Thistutorialwasoriginallywrittenfor
patorjk.combackin1999byAdamWehmann.Afterpatorjk.comwasresurrectedin2007,Idecidedtoputthetutorialbackupsinceithad
receivedsomepositivefeedback.Whenitwasputbackup,withAdam'sconcent,Icontributedthreenewsections:"TheSplitFunction","The
JoinFunction",and"MultidimensionalArrays".EverythingelsewaswrittenbyAdaminhisoriginal1999submission.
http://patorjk.com/programming/tutorials/vbarrays.htm 9/10
2/10/2017 VisualBasicArraysTutorial
http://patorjk.com/programming/tutorials/vbarrays.htm 10/10