Sei sulla pagina 1di 40

2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

Search
VisualBasic6(VB6)

HomeTutorials

UnderstandingArrays

Level:
WrittenByTheVBProgramerI'veupdateditsome.

DeclaringArrays

Arraysaredeclaredinthesamemannerasothervariables(i.e.,usingthekeywords"Dim","Private","Public",etc.),except
thatthearrayboundsarecodedinparenthesesfollowingthevariablename(ifafixedlengtharrayisbeingdeclared)oran
emptypairofparenthesesfollowthevariablename(ifavariablelength,ordynamicarrayisbeingdeclared).

Forfixedlengtharrays,youmustspecifytheupperboundofthearrayyoucanoptionallyspecifythelowerbound.By
default,thelowerboundis0(however,seethenoteonthe"OptionBase"statementfurtherbelow).Forvariablelength
arrays,youdonotspecifyanyboundsyoujustcodeanemptysetofparentheses.

Arrayscanhaveupto60dimensions(althoughitisrarethatyouwouldhavemorethanthreedimensionsoneortwois
thenorm).

Thesyntaxfordeclaringanarrayis:

[Dim|Private|Public|Static|Global]arrayname([lowerboundTo]upperbound[,])[Asdatatype]

http://www.vb6.us/tutorials/understandingarrays 1/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)


Sampledeclarationsforaonedimensionalarray:

ArrayDeclaration Notes

DimaintCount(9)AsInteger declaresa10elementarray,indexed0to9

DimaintCount(0To9)AsInteger sameasabove,withexplicitlowerbound

DimaintCount(1To10)AsInteger declaresa10elementarray,indexed1To10

DimaintCount(3To12)AsInteger declaresa10elementarray,indexed3To12

DimaintCount(4To5)AsInteger declaresa10elementarray,indexed4To5

DimaintCount()AsInteger declaresavariablelengtharraywhoseboundswill
bedeterminedatruntime

Notefromtheabovedeclarationsthatthelowerboundisnotrestrictedto0or1,anditcanevenbenegative.


Torefertoanindividualelementofanarrayinaproceduralstatement,placethedesiredindexinparenthesesnexttothearrayname.For
example,thefollowingstatementwilldisplaythe5thelementofaintCountontheform(assumingthefirstorseconddeclarationabove):

PrintaintCount(4)

Sampledeclarationsformultidimensionalarrays:

ArrayDeclaration Notes

DimasngSales(1To4,1To5)AsSingle declaresa2dimensionalarray(fourrows
indexed1to4,byfivecolumnsindexed1
to5)

DimasngResults(3,1To12,2To6)AsSingle declaresa3dimensionalarray(thefirst
dimensionhasfourelementsindexed0to
3,withinthat,theseconddimensionhas
12elementsindexed1to12,andwithin

http://www.vb6.us/tutorials/understandingarrays 2/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

that,thethirddimensionhasfive
elementsindexed2to6)



Torefertoanindividualelementofamultidimensionalarrayinaproceduralstatement,placethedesiredindicesinparenthesesnextto
thearrayname(youmusthaveoneindexperdimension,separatedbycommas).Examples:

PrintasngSales(2,3)
PrintasngResults(0,11,5)

OptionBase

Asexplainedabove,bydefault,ifyoudonotexplicitlycodealowerbound,thelowerboundofanarrayis0.However,thereisa
statementcalledOptionBase,which,ifyoucodeOptionBase1,willforceVBtodefaultthelowerboundofarraysto1.TheOption
Basestatementcanonlyhavethenumber0or1afterit,and0isthedefaultsoyouneverneedtocodeOptionBase0.TheOptionBase
statement,ifused,wouldbecodedatthebeginningofacodemoduleandisenforcedonlyatthemodulelevel.Recommendation:Do
notuseOptionBaseexplicitlycodethelowerboundofyourarraydeclarations.

InitializingArrays

Unfortunately,VB(upthroughversion6)doesnotprovideamechanismforinitializingarrays(oranyvariable)atthesame
timetheyaredeclaredinitializationcanonlybedonewithexecutableassignmentstatements.OlderversionsofBASIC
(priortoVB)providedapairofstatements(READandDATA)thatwouldenableyoutoloadasetofconstantdataitemsinto
anarrayfairlypainlesslyusingaFor/Nextloop.Butalas,READandDATAwereremovedfromthelanguagewhenVBcame
along.

Themostdirect(althoughtedious)waytoloadconstantdataintoanarrayiswithindividualassignmentstatements:

http://www.vb6.us/tutorials/understandingarrays 3/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

DimastrStateName(1To50)AsString

astrStateName(1)="ALASKA"

astrStateName(2)="ALABAMA"

astrStateName(49)="WESTVIRGINIA"

astrStateName(50)="WYOMING"

AnotherwaytodothisiswiththeArrayfunction,whichisconvenienttouse,butincurstheoverheadoftheVariant
datatype.Thewaytousethefunctionisasfollows:

First,declareaVariantvariabletoholdyourarray.Itmaybedeclaredwithorwithouttheopenparentheses.Recallthat
sinceVariantisthedefaultdatatype,the"AsVariant"clauseisoptional:

DimastrDayAbbrev()AsVariant

Second,usetheArrayfunctiontoassignalistofdataitemstothevariable:

astrDayAbbrev=Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat")

http://www.vb6.us/tutorials/understandingarrays 4/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

TheabovestatementwouldcauseastrDayAbbrevtobecomeanarraywithalowerboundof0or1(dependingonthe
settingofOptionBase)andanupperboundof6or7,accordingly.Fromthatpointon,astrDayAbbrevcouldbeused
likeastandardarray.

Example:LoadingandPrintingandArrayofRandomNumbers

ThefollowingexampleusesaFor/Nextlooptoloadanarrayof10integerswithrandomnumbersbetween1and100,then
usesasecondFor/Nextlooptoprintouttheresults.

DimaintRandomNum(1To10)AsInteger

DimintXAsInteger

Randomize

'loadthe"aintRandomNum"arraywithrandomnumbersbetween1and100...

ForintX=1To10

aintRandomNum(intX)=Int(100*Rnd+1)

Next

'displaythecontentsofthe"aintRandomNum"array...

ForintX=1To10

PrintaintRandomNum(intX)

http://www.vb6.us/tutorials/understandingarrays 5/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

Next

Ifdesired,setupa"TryIt"projectandplacethecodeshownintheaboveexampleinthecmdTryIt_Clickevent.Whenyou
runtheproject,yourresultswillresemblethefollowing:

DownloadtheVBprojectcodefortheexampleabovehere.

Example:LoadingaTwoDimensionalArrayfromaFileandPrintingItsContents

http://www.vb6.us/tutorials/understandingarrays 6/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

Thenextexamplereadsinafilecontainingfourweeksworthofsalesdata.Eachrecordrepresentsoneweekofdata.There
aresevenamountfieldsineachrecord,representingsalesamountsforSundaythroughSaturdayofeachweek.Theformat
ofthefileissequential,commadelimited.Itscontentsisasfollows:

1234,1765,3244,2453,2364,4567,3256

4646,1231,3466,2344,3446,3242,1231

1454,3466,1314,3464,2312,3466,6578

5453,4356,3453,3423,2355,2356,5534

Thesampleprogramreadsthisdataintoatwodimensional(7X4)array,andthenprintsitscontentsontheform.The
resultsoftherunisshownbelow:

http://www.vb6.us/tutorials/understandingarrays 7/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

Thecodebehindthe"TryIt"button(heavilydocumented)isasfollows:

PrivateSubcmdTryIt_Click()

'Declarea2dimensionalarrayconsistingof4rowsand7columns.

'Thefirstdimension(1to4)represents4weeks.Theseconddimension

'(1to7)represents7daysineachweek.

DimadblDailySales(1To4,1To7)AsDouble

'Declarevariablesforfileprocessing...

http://www.vb6.us/tutorials/understandingarrays 8/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

DimstrSalesFileNameAsString

DimstrBackSlashAsString

DimintSalesFileNbrAsInteger

'Declarevariablestobeusedtoaccesselementsofthearray...

DimintXAsInteger

DimintYAsInteger

'Setupthefilename...

strBackSlash=IIf(Right$(App.Path,1)="\","","\")

strSalesFileName=App.Path&strBackSlash&"SALES.DAT"

'Getanavailablefilehandle...

intSalesFileNbr=FreeFile

'Openthesalesfile...

OpenstrSalesFileNameForInputAs#intSalesFileNbr

'UseanestedFor/Nextlooptoloadthesalesdatafromthefile

'(onefieldatatime)intotheappropriateelementofthearray.

'The"outer"loop(usingintX)executesfourtimes,onceforeach

'recordinthefile...

ForintX=1To4

'The"inner"loop(usingintY)executesseventimesforeveryone

'executionoftheouterlooponceforeachfield(salesamount)

'intherecord...

http://www.vb6.us/tutorials/understandingarrays 9/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

ForintY=1To7

'NotethattheInput#statementspecifiesonlyoneitem:

'adblDailySales(intX,intY).Thiswillcausethecurrentfield

'ofthecurrentrecordtobestoredinthatelementofthearray.

'Thus,thisnestedloopwillcausethe"adblDailySales"arrayto

'beloadedinthefollowingsequence:

'(1,1)(1,2)(1,3)(1,4)(1,5)(1,6)(1,7)

'(2,1)(2,2)(2,3)(2,4)(2,5)(2,6)(2,7)

'(3,1)(3,2)(3,3)(3,4)(3,5)(3,6)(3,7)

'(4,1)(4,2)(4,3)(4,4)(4,5)(4,6)(4,7)

Input#intSalesFileNbr,adblDailySales(intX,intY)

Next

Next

'Closethesalesfile...

Close#intSalesFileNbr

'Printheadingsontheform.Printingwillbedoneusingthecommaseparator.

Print"Week#","Sun","Mon","Tue","Wed","Thu","Fri","Sat"

Print"","","","","","","",""

'UseanestedFor/Nextlooptoprintthesalesdatafromthearray.

'The"outer"loop(usingintX)executesfourtimes,onceforeach

http://www.vb6.us/tutorials/understandingarrays 10/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

'"row"ofthearray...

ForintX=1To4

'Print"intX"itself,whichidentifiestheweekbeingprinted.Byendingthe

'Printstatementwithacomma,theprintpositionwillnotadvancetothenext

'linerather,thenextitemwillprintinthenextprint"zone".

PrintintX,

'The"inner"loop(usingintY)executesseventimesforeveryone

'executionoftheouterlooponceforeach"column"(salesamount)

'inthecurrent"row"...

ForintY=1To7

'Printthecurrentelementofthearray.Again,byendingthePrint

'statementwithacomma,theprintpositionwillnotadvancetothenext

'linerather,thenextitemwillprintinthenextprint"zone".

PrintadblDailySales(intX,intY),

Next

'ThePrintstatementbyitselfwillforcealinebreak.

Print

Next

EndSub

http://www.vb6.us/tutorials/understandingarrays 11/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

DownloadtheVBprojectcodefortheexampleabovehere.

Examples:UsingReDimandReDimPreserve

Whenyoudon'tknowinadvancehowmanyarrayelementsyouwillneed,suchaswhenloadingdatafromafileorfrom
keyboardinput,youcanusedynamicarrays.YouchangethesizeofadynamicarraywiththeReDimstatement(withor
withoutthePreserveoption).Thesyntaxis:

ReDim[Preserve]varname(subscripts)[Astype]

TheReDimstatement(withoutthePreserveoption)resizesanarray,butdoesnotretainanyvaluespreviouslyloadedinto
thearray,whichmakesitnotasusefulasReDimPreserve.

YoucoulduseReDimbyitselfwhenyoudon'tknowhowbigthearrayshouldbeatdesigntime,butyouobtainthesize
priortoloadingthearray.

Followingisanexamplewhichcalculatestheaveragetemperaturefromaseriesoftemperaturesinputbytheuserbut
theuserispromptedinadvanceforthenumberoftemperaturestobeentered.

DimaintTemperatures()AsInteger

DimintNbrToEnterAsInteger

DimintXAsInteger

http://www.vb6.us/tutorials/understandingarrays 12/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

DimlngTotTempAsLong

DimdblAvgTempAsDouble

intNbrToEnter=Val(InputBox("Numberoftemperaturestobeentered:"))

IfintNbrToEnter=0ThenExitSub

ReDimaintTemperatures(1TointNbrToEnter)

ForintX=1TointNbrToEnter

aintTemperatures(intX)=Val(InputBox("Temperature#"&intX&":"))

Print"Temperature#"&intX&":"&aintTemperatures(intX)

lngTotTemp=lngTotTemp+aintTemperatures(intX)

Next

dblAvgTemp=lngTotTemp/intNbrToEnter

Print

Print"Theaveragetemperatureenteredwas"&Format$(dblAvgTemp,"Fixed")

Ifdesired,setupa"TryIt"projectandplacethecodeshownintheaboveexampleinthecmdTryIt_Clickevent.Whenyou
runtheproject,yourresultswillresemblethefollowing:

First,youwillbepromptedtoinputthenumberofvaluestobeentered:

http://www.vb6.us/tutorials/understandingarrays 13/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

Next,youwillbepromptedrepeatedly(thenumberoftimesyouspecifiedinthefirstprompt7inthiscase)fora
temperaturetoenter:

Whenyoufinishenteringallthetemperatures,theaveragewillbeprinted:

http://www.vb6.us/tutorials/understandingarrays 14/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

DownloadtheVBprojectcodefortheexampleabovehere.

ReDimwiththePreserveoptionisusefulwhenyoudon'tknowinadvancehowmanyitemswillbeinput.Whenyouuse
ReDimPreserve,youtypicallyaredynamicallychanging(increasing)theupperboundofthearrayinaloopasyouloadthe
array.FollowingisanexampleofhowthepreviousexamplecouldbemodifiedtouseReDimPreserve.Notethatwithin
theinputloop,thevariable"intX"isincrementedby1.ThenReDimPreserveisusedtoresizetheaintTemperaturesarray
usingthenewvalueofintX.

DimaintTemperatures()AsInteger

DimintCurrTempAsInteger

DimintNbrOfEntriesAsInteger

http://www.vb6.us/tutorials/understandingarrays 15/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

DimintXAsInteger

DimlngTotTempAsLong

DimdblAvgTempAsDouble

intCurrTemp=Val(InputBox("Enteratemperature(0toquit):"))

DoUntilintCurrTemp=0

intX=intX+1

ReDimPreserveaintTemperatures(1TointX)

aintTemperatures(intX)=intCurrTemp

Print"Temperature#"&intX&":"&aintTemperatures(intX)

lngTotTemp=lngTotTemp+aintTemperatures(intX)

intCurrTemp=Val(InputBox("Enteratemperature(0toquit):"))

Loop

IfintX=0ThenExitSub

dblAvgTemp=lngTotTemp/intX

Print

Print"Theaveragetemperatureenteredwas"&Format$(dblAvgTemp,"Fixed")

http://www.vb6.us/tutorials/understandingarrays 16/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

Ifdesired,setupa"TryIt"projectandplacethecodeshownintheaboveexampleinthecmdTryIt_Clickevent.Whenyou
runtheproject,yourresultswillbesimilartothepreviousexample.

DownloadtheVBprojectcodefortheexampleabovehere.

Example:LoadingaUDTArrayfromaFileandPrintingItsContents

Itisoftenusefultoworkwiththecontentsofasetofdata(beitthecontentsofasmalltextfileortherecordsetresultsof
adatabasequery)inaUDTarray,wherethestructureoftheUDTarraymirrorsthestructureofthefieldsofthedatasetto
beworkedwith.

Inthenextexample,thecontentsofthe"EMPLOYEE.DAT"file(commadelimitedversion)thatwehaveworkedwithin
someoftheprevioustopicswillbeloadedintoaUDTarray,andthenitscontentswillbeprintedontheform.

Thecodelistingforthesampleprogramisshownbelow.Explanationsofpertinentpartsoftheprogramwillthenfollow.

OptionExplicit

PrivateTypeEmployeeRecord

EmpNameAsString

DeptNbrAsInteger

JobTitleAsString

HireDateAsDate

http://www.vb6.us/tutorials/understandingarrays 17/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

HrlyRateAsSingle

EndType

PrivatemaudtEmpRecord()AsEmployeeRecord

PrivateSubcmdClear_Click()

Cls

EndSub

PrivateSubcmdExit_Click()

End

EndSub

PrivateSubcmdTryIt_Click()

DimstrEmpFileNameAsString

DimstrBackSlashAsString

DimintEmpFileNbrAsInteger

DimintRecCountAsInteger

http://www.vb6.us/tutorials/understandingarrays 18/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

DimintXAsInteger

strBackSlash=IIf(Right$(App.Path,1)="\","","\")

strEmpFileName=App.Path&strBackSlash&"EMPLOYEE.DAT"

intEmpFileNbr=FreeFile

OpenstrEmpFileNameForInputAs#intEmpFileNbr

intRecCount=0

DoUntilEOF(intEmpFileNbr)

intRecCount=intRecCount+1

ReDimPreservemaudtEmpRecord(1TointRecCount)

WithmaudtEmpRecord(intRecCount)

Input#intEmpFileNbr,.EmpName,_

.DeptNbr,_

.JobTitle,_

.HireDate,_

.HrlyRate

EndWith

Loop

Close#intEmpFileNbr

ForintX=LBound(maudtEmpRecord)ToUBound(maudtEmpRecord)

WithmaudtEmpRecord(intX)

http://www.vb6.us/tutorials/understandingarrays 19/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

Print.EmpName_

Tab(25)Format$(.DeptNbr,"@@@@")_

Tab(35).JobTitle_

Tab(55)Format$(.HireDate,"mm/dd/yyyy")_

Tab(70)Format$(Format$(.HrlyRate,"Standard"),"@@@@@@@")

EndWith

Next

EndSub

IntheGeneralDeclarationssection(after"OptionExplicit",butbeforeanySuborFunctionisdefined),theUserDefined
Type"EmployeeRecord"isdeclared:

PrivateTypeEmployeeRecord

EmpNameAsString

DeptNbrAsInteger

JobTitleAsString

HireDateAsDate

HrlyRateAsSingle

EndType

ThisisfollowedbythedeclarationoftheUDTvariable"maudtEmpRecord"("As"datatype"EmployeeRecord").Notethat
"maudtEmpRecord"isdeclaredwithapairofemptyparenthesesafteritsname,indicatingthatthiswillbeadynamicarray.

http://www.vb6.us/tutorials/understandingarrays 20/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

PrivatemaudtEmpRecord()AsEmployeeRecord

IntheinputloopthatloadstherecordsfromthefileintotheUDTarray,notethatthetechniqueusedintheprevious
exampletoincreasetheupperboundofthedynamicarrayisusedhereaswell.Thevariable"intRecCount"isincremented
by1,thenReDimPreserveisusedtoresizethemaudtEmpRecordarrayusingthenewvalueofintRecCount.

intRecCount=intRecCount+1

ReDimPreservemaudtEmpRecord(1TointRecCount)

Thisisfollowedbythecodetoloadthefieldsofthecurrentinputrecordintothecorrespondingitemsofthecurrent
elementofthemaudtEmpRecordarray.NotethataWith/EndWithblockisusedto"factorout"thereferenceto
"maudtEmpRecord(intRecCount)".

WithmaudtEmpRecord(intRecCount)

Input#intEmpFileNbr,.EmpName,_

.DeptNbr,_

.JobTitle,_

.HireDate,_

.HrlyRate

EndWith

IfWith/EndWithwasnotused,thestatementabovewouldhavetobewrittenasfollows:

http://www.vb6.us/tutorials/understandingarrays 21/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

Input#intEmpFileNbr,maudtEmpRecord(intRecCount).EmpName,_

maudtEmpRecord(intRecCount).DeptNbr,_

maudtEmpRecord(intRecCount).JobTitle,_

maudtEmpRecord(intRecCount).HireDate,_

maudtEmpRecord(intRecCount).HrlyRate

ThelastportionoftheprogramloopsthroughtheUDTarrayandprintsitscontentsontheform.The"For"statement
introducestheLBoundandUBoundfunctions,whichdeterminethelowerandupperbounds,respectively,ofanarray.
(Inthiscase,"LBound(maudtEmpRecord)"wouldevaluateto1,and"LBound(maudtEmpRecord)"wouldevaluatetothe
valueofintRecCount.)TheLBoundandUBoundfunctionsareexaminedingreaterdetailalittlefurtherbelow.Again,a
With/EndWithblockisusedto"factorout"thereferenceto"maudtEmpRecord(intX)".

ForintX=LBound(maudtEmpRecord)ToUBound(maudtEmpRecord)

WithmaudtEmpRecord(intX)

Print.EmpName_

Tab(25)Format$(.DeptNbr,"@@@@")_

Tab(35).JobTitle_

Tab(55)Format$(.HireDate,"mm/dd/yyyy")_

Tab(70)Format$(Format$(.HrlyRate,"Standard"),"@@@@@@@")

EndWith

Next

http://www.vb6.us/tutorials/understandingarrays 22/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

Whenthesampleprogramisrun,itsoutputissimilartothatofpreviousfileprocessingsampleprograms:

DownloadtheVBprojectcodefortheexampleabovehere.

MoreonReDimandReDimPreserve(fromtheMSDN/VBHelp)

TheReDimstatementisusedtosizeorresizeadynamicarraythathasalreadybeenformallydeclaredusingaPrivate,
Public,orDimstatementwithemptyparentheses(withoutdimensionsubscripts).YoucanusetheReDimstatement
repeatedlytochangethenumberofelementsanddimensionsinanarray.ReDimsetsVariantarraystoEmpty,numeric
arraysto0,stringarraysto""andobjectarraystoNothing.

http://www.vb6.us/tutorials/understandingarrays 23/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

IfyouusethePreservekeyword,youcanresizeonlythelastarraydimensionandyoucan'tchangethenumberof
dimensionsatall.Forexample,ifyourarrayhasonlyonedimension,youcanresizethatdimensionbecauseitisthelast
andonlydimension.However,ifyourarrayhastwoormoredimensions,youcanchangethesizeofonlythelastdimension
andstillpreservethecontentsofthearray.Thefollowingexampleshowshowyoucanincreasethesizeofthelast
dimensionofadynamicarraywithouterasinganyexistingdatacontainedinthearray.

ReDimX(10,10,10)

...

ReDimPreserveX(10,10,15)

Similarly,whenyouusePreserve,youcanchangethesizeofthearrayonlybychangingtheupperboundchangingthe
lowerboundcausesanerror.

Ifyoumakeanarraysmallerthanitwas,dataintheeliminatedelementswillbelost.

TheEraseStatement

TheErasestatementisusedtoclearthecontentsofadynamicarray.Thesyntaxis:

Erasearrayname

http://www.vb6.us/tutorials/understandingarrays 24/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

Example:

EraseaintTemperatures

TheLBoundandUBoundFunctions

YoucanusetheLBoundandUBoundfunctionstodeterminethelowerandupperbounds,respectively,ofanarray.The
syntaxis:

LBound(arrayname[()][,dimension])

UBound(arrayname[()][,dimension])

Notethatthearraynamemaybespecifiedwithorwithoutasetofemptyparentheses.Thesecondparameter,whichis
optional,specifieswhichdimensionofthearrayyouwanttheboundof,whichcanbeusefulifyouhaveamultidimensional
array.Ifdimensionisomitted,1isassumed.

Forexample,ifyouhaveanarraydeclaredas:

DimaintTemperatures(1To7)AsInteger

Thenthestatement

PrintLBound(aintTemperatures)

http://www.vb6.us/tutorials/understandingarrays 25/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

wouldprint1

Andthestatement

PrintUBound(aintTemperatures)

wouldprint7.

Foranotherexample,ifyouhaveanarraydeclaredas:

DimaintTemperatures(1To7,5To4)AsInteger

Thenthestatement

PrintLBound(aintTemperatures,2)

wouldprint5

Andthestatement

PrintUBound(aintTemperatures,2)

wouldprint4.

TheLBoundandUBoundfunctionsareusefulwhenyouneedtoloopthroughadynamicarrayafterithasbeenloaded.For
example,sayyouloadedthedynamicarrayinaninitialSubwhentheprogrambegan,andthenlater,insomeotherSub,
youneedtoprocessitsvalues.IfyouusedlocalvariablestosettheboundsofthearraywithReDimPreserveintheinitial
Sub,youwon'tknowhowmanyelementsthearraycontainswhenyouneedtoprocessthearrayintheotherSub

http://www.vb6.us/tutorials/understandingarrays 26/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

(becausethevaluesofthelocalvariableswouldnotberetainedonceyouleavetheinitialSub).LBoundandUBoundcan
helpinthatsituation:

ForintX=LBound(maintTemperatures)ToUBound(maintTemperatures)

'processmaintTemperatures(intX)

Next

TheLBoundandUBoundfunctionsarealsoneededwhenyoumustprocessanarraythathasbeenpassedtoaSubor
Function,becausetheboundsofthearraycannotbespecifiedintheSuborFunctionheader'sargumentlist.Thereason
thattheboundsofanarraycannotbespecifiedinaSuborFunctionheader'sargumentlististhatthesameSubor
Functioncanbeusedtoprocessarraysofdifferentsizes.Therefore,youshouldusetheLBoundandUBoundfunctionsin
theSuborFunctiontodeterminetheboundsofthearraythathasbeenpassed.

Examples:HandlinganEmptyArray

Ifadynamicarrayhasnoelements(i.e.,aReDimorReDimPreservestatementwasneverexecutedonit),whenyou
subsequentlyattempttoreferenceanelementofthatarrayorifyouattempttouseLBoundorUBoundonthatarray,a
runtimeerror'9'(Subscriptoutofrange)errorwilloccur.

Forexample,let'stakethesampleemployeefileprocessingprogramaboveandmodifyittoreadinanemptyfile:

strEmpFileName=App.Path&strBackSlash&"EMPTY.DAT"

Thestatementswithintheinputloopthatstartswith:

http://www.vb6.us/tutorials/understandingarrays 27/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

DoUntilEOF(intEmpFileNbr)

willneverbeexecuted,becauseEOF(endoffile)willbetriggeredassoonasthefileisopened.Thismeansthatthe
maudtEmpRecordarraywillneverbeloaded.

Whentheprogramtriestoreferenceitwiththisstatement:

ForintX=LBound(maudtEmpRecord)ToUBound(maudtEmpRecord)

theruntimeerrorwilloccur:

DownloadtheVBprojectcodefortheexampleabovehere.

http://www.vb6.us/tutorials/understandingarrays 28/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

Therearetwowaysthiserrorcanbehandled.Thefirstistoadderrorhandlingcodetotheprocedure,asshownbelow:

PrivateSubcmdTryIt_Click()

DimstrEmpFileNameAsString

DimstrBackSlashAsString

DimintEmpFileNbrAsInteger

DimintRecCountAsInteger

DimintXAsInteger

OnErrorGoTocmdTryIt_Click_Error

strBackSlash=IIf(Right$(App.Path,1)="\","","\")

strEmpFileName=App.Path&strBackSlash&"EMPTY.DAT"

intEmpFileNbr=FreeFile

OpenstrEmpFileNameForInputAs#intEmpFileNbr

intRecCount=0

DoUntilEOF(intEmpFileNbr)

intRecCount=intRecCount+1

ReDimPreservemaudtEmpRecord(1TointRecCount)

WithmaudtEmpRecord(intRecCount)

Input#intEmpFileNbr,.EmpName,_

.DeptNbr,_

http://www.vb6.us/tutorials/understandingarrays 29/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

.JobTitle,_

.HireDate,_

.HrlyRate

EndWith

Loop

Close#intEmpFileNbr

'Thefollowingstatementwillcausetheerrorhandlingcode

'toexecute...

ForintX=LBound(maudtEmpRecord)ToUBound(maudtEmpRecord)

WithmaudtEmpRecord(intX)

Print.EmpName_

Tab(25)Format$(.DeptNbr,"@@@@")_

Tab(35).JobTitle_

Tab(55)Format$(.HireDate,"mm/dd/yyyy")_

Tab(70)Format$(Format$(.HrlyRate,"Standard"),"@@@@@@@")

EndWith

Next

cmdTryIt_Click_Exit:

ExitSub

cmdTryIt_Click_Error:

IfErr.Number=9Then

http://www.vb6.us/tutorials/understandingarrays 30/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

Print"Filewasempty."

Else

MsgBox"Thefollowingerroroccurred:"&vbNewLine_

&"Error#"&Err.Number&""&Err.Description,_

vbCritical,_

"Error"

EndIf

ResumecmdTryIt_Click_Exit

EndSub

Whentheprogramruns,theappropriatemessagewillbedisplayed,asshownbelow:

http://www.vb6.us/tutorials/understandingarrays 31/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

DownloadtheVBprojectcodefortheexampleabovehere.

ThesecondwaytohandlethisistousetheSafeArrayGetDimWindowsAPI.Inmyview,thisisacleanerandmore
precisewayofhandlingtheemptyarrayissue.

Onceagain,thecodeforthesampleprogramisshowninitsentiretybelow,withthemodificationsneededtousethe
SafeArrayGetDimfunctionbolded.NotethattheAPIdeclarationforthefunctionmustbemadeintheGeneralDeclarations
sectionoftheprogram.Lateron,thefollowingsyntaxisused:

IfSafeArrayGetDim(arrayname)>0Then...

http://www.vb6.us/tutorials/understandingarrays 32/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

Thefunctionwillreturn0ifthearrayisempty,apositivenumberifthearrayispopulated.

OptionExplicit

PrivateDeclareFunctionSafeArrayGetDimLib"oleaut32.dll"_

(ByRefsaArray()AsAny)AsLong

PrivateTypeEmployeeRecord

EmpNameAsString

DeptNbrAsInteger

JobTitleAsString

HireDateAsDate

HrlyRateAsSingle

EndType

PrivatemaudtEmpRecord()AsEmployeeRecord

PrivateSubcmdClear_Click()

Cls

EndSub

http://www.vb6.us/tutorials/understandingarrays 33/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

PrivateSubcmdExit_Click()

End

EndSub

PrivateSubcmdTryIt_Click()

DimstrEmpFileNameAsString

DimstrBackSlashAsString

DimintEmpFileNbrAsInteger

DimintRecCountAsInteger

DimintXAsInteger

strBackSlash=IIf(Right$(App.Path,1)="\","","\")

strEmpFileName=App.Path&strBackSlash&"EMPTY.DAT"

intEmpFileNbr=FreeFile

OpenstrEmpFileNameForInputAs#intEmpFileNbr

intRecCount=0

DoUntilEOF(intEmpFileNbr)

intRecCount=intRecCount+1

ReDimPreservemaudtEmpRecord(1TointRecCount)

http://www.vb6.us/tutorials/understandingarrays 34/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

WithmaudtEmpRecord(intRecCount)

Input#intEmpFileNbr,.EmpName,_

.DeptNbr,_

.JobTitle,_

.HireDate,_

.HrlyRate

EndWith

Loop

Close#intEmpFileNbr

IfSafeArrayGetDim(maudtEmpRecord)>0Then

ForintX=LBound(maudtEmpRecord)ToUBound(maudtEmpRecord)

WithmaudtEmpRecord(intX)

Print.EmpName_

Tab(25)Format$(.DeptNbr,"@@@@")_

Tab(35).JobTitle_

Tab(55)Format$(.HireDate,"mm/dd/yyyy")_

Tab(70)Format$(Format$(.HrlyRate,"Standard"),"@@@@@@@")

EndWith

Next

Else

http://www.vb6.us/tutorials/understandingarrays 35/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

Print"Filewasempty."

EndIf

EndSub

Whentheprogramruns,theappropriatemessagewillbedisplayed,asshownbelow:

DownloadtheVBprojectcodefortheexampleabovehere.

PosttoFacebook

http://www.vb6.us/tutorials/understandingarrays 36/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

PosttoTwitter
AddtoLinkedIn

Ifyouenjoyedthispost,subscribeforupdates(it'sfree)
EmailAddress... Subscribe

programming Fri,07/22/201106:49achime(notverified)

tnxalotmwah!

textboxarrays Wed,08/25/201023:04jaycee27(notverified)

couldyouplspostacodewherewhenyouclickaniteminadatagridtheitemshouldbeputinatextboxarrays.

HowtocodethisProgrammingChallange Sat,01/16/201012:33InderMohan(notverified)

Youaregivenamapasastring.Themaprepresentsanoceanwithsomenumberofislands.Forexample:

.........
.XX....X.
XXX..XX..
.X.......
...XXX...
Onthemap,"X"representsland,while"."representswater.Thegridwillberectangularwithwidth<=50charactersand
height<=50characters.Assumethatitwillbepassedasanarrayofstrings,withonelineofthemapineachelementof
thearray.
http://www.vb6.us/tutorials/understandingarrays 37/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

Yourprogrammustreturnthenumberofdistinctislands.Anislandisdefinedasanysectionoflandconnectedbyadjacent
"X"characters(adjacentmeaningonecharacterup,down,left,orrightwithnowraparoundoranything).Donotcount
diagonallyadjacentlandasconnected.Forexample,theabovemapshouldreturn4.Justtoclarifywhatcountsasan
island:

.........
.11....3.
111..22..
.1.......
...444...
So,tobeclear,youneedtowriteafunctionthattakesanarrayofstringslikethemapabove,andreturnsoneinteger:the
numberofislandsfound.Ifyouneedfurtherclarification,feelfreetocontactme.Thesolutionswillbejudgedmanually
(justemailittome),soifthere'ssomesmallthingyou'veunderstooddifferentlythanintended,wecanworryaboutthat
then.

Anyways,goodluck!

MoreExamples

XXXXXXXX
X......X
X.XXXX.X
X......X
XXXXXXXX

Shouldreturn2islandsmightcontainotherislands.

Shouldreturn1nowater,butstillanisland.

.............

Shouldreturn0.

X.X.X.X.
.X.X.X.X
X.X.X.X.
.X.X.X.X

http://www.vb6.us/tutorials/understandingarrays 38/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

Shouldreturn16.

Showmethesolution Mon,07/18/201102:18Anonymous(notverified)

I'mveryinterestedwiththeproblemandIwouldreallylovetolearnthesolution.Myknowledgeofarraysasofnowis
kindofstillthethebeginningstage,soithinklearningthiswouldenablemetocreateabigleaptowardsmasteringit.
Thankyou.

ArrayTutorial Sun,11/16/200807:56Chew(notverified)

LOVEDIT!!

NowI'manexpertonArrays.

Arrays Mon,07/26/201001:45Anonymous(notverified)

DearSir

Couldyouplsadvisethecodeforthearraytoholdthevaluesof"itemswhicharecheckedinagridcontrol"and
retrieveonlythedatawhichmeetsthesevaluesfromthesqltable.

Willbealotofgreatnessofyou!

Rgds

Sanjeeb

http://www.vb6.us/tutorials/understandingarrays 39/40
2/10/2017 UnderstandingArrays|VisualBasic6(VB6)

Array.zipnotdownloadable Tue,05/27/200821:45DBauer(notverified)

Example:LoadingaTwoDimensionalArrayfromaFileandPrintingItsContents
igetanerrorwhenitrytodownloadthearray.zip

Unlessotherwisenoted,allcontentonthissiteandinthesourcesamplesisCopyrighted2011bytheownerofvb6.us.
AllrightsreservedContactInformation

http://www.vb6.us/tutorials/understandingarrays 40/40

Potrebbero piacerti anche