You are on page 1of 10

2/10/2017 VisualBasicArraysTutorial

Visual Basic Array Tutorial


By Adam Wehmann

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

Dim strCDRack(0 to 2) As String

You'vejustmadeavariable'strCDRack'thatcontainsthreeslots(#0,#1,and#2)andisofaStringdatatype.NowyoucaninsertyourCDsinto
it:

Dim strCDRack(0 to 2) As String

strCDRack(0) = "Deftones"
strCDRack(1) = "Tool"
strCDRack(2) = "Disturbed"

Noticethateachofthethreenewlinesstartsoffwiththevariablenameandthengivesanelementnumberbeforehavingavalueassigned.This
islikenumberingtheslotsonyourCDrackstartingat0upto2andtheninsertingaCDintoeachslot.Theformatfordeclaringanarrayis:

Dim|Public|PrivateArrayName(Subscript)AsDataType

Dim , Public ,and Private declarethearrayanditsscope.Using Dim inaprocedurewillmakethearrayonlyavailablefromwithinthat


procedure.UsingitintheGeneralDeclarationssectionwillmakeitavailabletoallproceduresinthatmodule. Private hasthesameeffect
andshouldbeusedonlyatthemodularlevel.Using Public willmakethearrayavailablethroughouttheproject.
ArrayNameisthenameofthearray.
Subscriptisthedimensionsofthearray.
DataTypeisanyvaliddatatype.

Dynamic Arrays
ThenewCharlotteChurchCDcameoutbutyourrackonlyhasthreeslots.Youdon'twanttothrowawayanyofyourCDstomakeroomforthe
newonesoyoudecidetouseyourultimatebuildingskillstoattachanotherslot.Youstartbuilding:

Dim strCDRack() As String

ReDim strCDRack(0 to 2) As String

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:

Dim strCDRack() As String

ReDim strCDRack(0 to 2) As String

strCDRack(0) = "Deftones"
strCDRack(1) = "Tool"
strCDRack(2) = "Disturbed"

ReDim Preserve strCDRack(0 to 3) As String

strCDRack(3) = "Charlotte Church"

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.)

Retrieving the Contents of an Array


Nowthatyouknowhowtobuildanarray,youmightaskhowtoretrieveitscontents.Sayyou'vebuiltanarrayofyourfriends'names:

http://patorjk.com/programming/tutorials/vbarrays.htm 3/10
2/10/2017 VisualBasicArraysTutorial

Dim strFriends(0 to 6) As String

strFriends(0) = "Bianca"
strFriends(1) = "Jeana"
strFriends(2) = "Sam"
strFriends(3) = "Jenna"
strFriends(4) = "Erin"
strFriends(5) = "Carolyn"
strFriends(6) = "Kate"

That'sallgoodanddandybutyouwanttodisplaytheirnamesinsuccessivemessageboxes,soyouconstructaloop:

Dim strFriends(0 to 6) As String, lngPosition as Long

strFriends(0) = "Bianca"
strFriends(1) = "Jeana"
strFriends(2) = "Sam"
strFriends(3) = "Jenna"
strFriends(4) = "Erin"
strFriends(5) = "Carolyn"
strFriends(6) = "Kate"

For lngPosition = LBound(strFriends) To UBound(strFriends)

MsgBox strFriends(lngPosition)

Next lngPositionlngPositionlngPosition

Therearetwonewfunctionsinthatsnippetofcode. LBound and UBound areusedtodeterminethelowerandupperboundsofanarray.


BecausestrFriendshasalowerboundof0andanupperboundof6.Thesefunctionsallowyoutotoiteratethroughanarraywithadynamic
sizeandtheykeepyoufromhavingtokeeptrackofthearray'ssizeyourself.Witheachiterationofthatloop,lngPositionwillcountupfrom0to
6.Byaccessingthearrayas strFriends(lngPosition) youaregreatlyreducingtheamountofcodeyouhavetowrite.

Adding New Elements on the Fly


Sometimesyouhaveanarraythatneedstokeepgrowing,andyoudon'tknowwhattheupperboundwillendupbeing.Maybeyouaremakinga
crappyMP3playerandneedtoasktheusertoinputsongnames.Youmightdosomethinglikethis:

http://patorjk.com/programming/tutorials/vbarrays.htm 4/10
2/10/2017 VisualBasicArraysTutorial

Dim strSongNames() As String 'Array of song names


Dim blDimensioned As Boolean 'Is the array dimensioned?
Dim strText As String 'To temporarily hold names
Dim lngPosition as Long 'Counting

'The array has not yet been dimensioned:


blDimensioned = False

Do

'Ask for a song name


strText = InputBox("Enter a song name:")

If strText <> "" Then

'Has the array been dimensioned?


If blDimensioned = True Then

'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

'No, so dimension it and flag it as dimensioned.


ReDim strSongNames(0 To 0) As String
blDimensioned = True

End If

'Add the song name to the last element in the array.


strSongNames(UBound(strSongNames)) = strText

End If

Loop Until strText = ""

'Display entered song names:

For lngPosition = LBound(strSongNames) To UBound(strSongNames)

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:

Dim strFriends(0 to 2) As String

strFriends(0) = "Bianca"
strFriends(1) = "Jeana"
strFriends(2) = "Erin"

Erase strFriends

The Split Function


Sometimeswerunintosituationswherewewanttotaketheinformationfromwithinagivenstring,separateitintomultiplestrings,andthen
placethosestringsinanarray.Forexample,saywehadthiscode:

Dim cdList As String


cdList = "Nevermind, OK Computer, I Care Because You Do, Icky Thump"

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:

Dim strCDRack() As String


Dim cdList As String
Dim i As Integer

cdList = "Nevermind, OK Computer, I Care Because You Do, Icky Thump"


strCDRack = Split(cdList, ", ")

For i = LBound(strCDRack) To UBound(strCDRack)

MsgBox strCDRack(i)

Next

The Join Function


The split functionallowedustobreakstringsdownintoarrays,isthereafunctionthatallowsustotakearraysandmakethemonebiglong
string?Yes,yesthereis,anditiscalled join . join isaverysimplefunction.Ithasthefollowingsyntax:

StringName=join(ArrayInput[,Delimiter])

ArrayInputisthearraythatyouwanttoplaceintoastring.
Delimiterisanoptionalparameterthatindicateswhatyouwanttoplacebetweenelementsareaddedtothestring.Bydefaultthis
parameterissetto"".

Usingoneofourpreviousexamples,hereissomesamplecodeonhowonemightusejoin:

http://patorjk.com/programming/tutorials/vbarrays.htm 7/10
2/10/2017 VisualBasicArraysTutorial

Dim strFriends(0 to 6) As String, lngPosition as Long

strFriends(0) = "Bianca"
strFriends(1) = "Jeana"
strFriends(2) = "Sam"
strFriends(3) = "Jenna"
strFriends(4) = "Erin"
strFriends(5) = "Carolyn"
strFriends(6) = "Kate"

Dim myFriends As String

'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

' A CD rack for the Beatles


cdRack(0, 0) = "Rubber Soul"
cdRack(0, 1) = "Revolver"
cdRack(0, 2) = "The White Album"
cdRack(0, 3) = "Let It Be"

' A CD rack for the Rolling Stones


cdRack(1, 0) = "Sticky Fingers"
cdRack(1, 1) = "Beggars Banquet"
cdRack(1, 2) = "Let It Bleed"
cdRack(1, 3) = "Tattoo You"

ThefirstitemofthefirstdimensionisanarrayforBeatlesCDswhiletheseconditemofthefirstdimensionisanarrayforRollingStonesCDs.
Youcouldalsoaddathirddimensionifyouwanted.KeepingwithourCDrackanalogy,youcouldpicturethisthirddimensionasahallwaywith
severalrooms.InsideofeachroomwouldbearowofCDsracks.Ifyouwantedyourhallwaystohave10rooms,eachwithCDrackslikethe
http://patorjk.com/programming/tutorials/vbarrays.htm 8/10
2/10/2017 VisualBasicArraysTutorial

onesintheaboveexample,youcoulddeclareyourarrayasfollows:

Dim cdRackHallway(0 to 9, 0 to 1, 0 to 3) As String

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

' A CD rack for the Beatles


cdRack(0, 0) = "Rubber Soul"
cdRack(0, 1) = "Revolver"
cdRack(0, 2) = "The White Album"
cdRack(0, 3) = "Let It Be"

' A CD rack for the Rolling Stones


cdRack(1, 0) = "Sticky Fingers"
cdRack(1, 1) = "Beggars Banquet"
cdRack(1, 2) = "Let It Bleed"
cdRack(1, 3) = "Tattoo You"

ReDim Preserve cdRack(0 to 1, 0 to 4) As String

' Lets add another Beatles CD


cdRack(0, 4) = "Abby Road"

' Lets add another Rolling Stones CD


cdRack(1, 4) = "Exile on Main St."

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

MoreVBResources Appsfrompatorjk.com Social


VisualBasic6.0Examples TexttoASCIIArtGenerator Tweet(https://twitter.com/share)
(http://patorjk.com/programming/vb6examples.htm)
(http://patorjk.com/software/taag/)
VisualBasic6.0CodeBank KeyboardLayoutAnalyzer
(http://patorjk.com/programming/tutorials/vb6codebank.htm)
(http://patorjk.com/keyboard
Pat'sBlog layoutanalyzer/)
(http://patorjk.com/blog/) JavaScriptSnakeGame
(http://patorjk.com/games/snake/)
ScrollingTextTimeWaster!
(http://patorjk.com/misc/scrollingtext/timewaster.php)

http://patorjk.com/programming/tutorials/vbarrays.htm 10/10

You might also like