visual basic scripting - documentation.help · microsoft® visual basic® scripting edition looping...
TRANSCRIPT
Microsoft®VisualBasic®ScriptingEdition
FeatureInformation
VBScriptLanguageReferenceVersionInformation
VBScriptFeaturesVBAFeaturesnotinVBScriptVBScriptFeaturesnotinVBAMicrosoftScriptingRun-TimeFeatures
Microsoft®VisualBasic®ScriptingEdition
AlphabeticKeywordList
VBScriptLanguageReferenceVersionInformation
AbsFunctionAdditionOperator(+)AndOperatorArrayFunctionAscFunctionAssignmentOperator(=)AtnFunctionCallStatementCBoolFunctionCByteFunctionCCurFunctionCDateFunctionCDblFunctionChrFunctionCIntFunctionClassObjectClassStatementClearMethodCLngFunctionColorConstantsComparisonConstantsConcatenationOperator(&)ConstStatementCosFunctionCreateObjectFunctionCSngFunctionCStrFunctionDateandTimeConstantsDateFormatConstants
DateFunctionDateAddFunctionDateDiffFunctionDatePartFunctionDateSerialFunctionDateValueFunctionDayFunctionDescriptionPropertyDictionaryObjectDimStatementDivisionOperator(/)Do...LoopStatementEmptyEqvOperatorEraseStatementErrObjectEvalFunctionExecuteMethodExecuteStatementExitStatementExpFunctionExponentiationOperator(^)FalseFileSystemObjectObjectFilterFunctionFirstIndexPropertyFixFunctionFor...NextStatementForEach...NextStatementFormatCurrencyFunctionFormatDateTimeFunctionFormatNumberFunctionFormatPercentFunctionFunctionStatementGetObjectFunctionGetRefFunctionGlobalProperty
HexFunctionHelpContextPropertyHelpFilePropertyHourFunctionIf...Then...ElseStatementIgnoreCasePropertyImpOperatorInitializeEventInputBoxFunctionInStrFunctionInStrRevFunctionIntFunctionIntegerDivisionOperator(\)IsOperatorIsArrayFunctionIsDateFunctionIsEmptyFunctionIsNullFunctionIsNumericFunctionIsObjectFunctionJoinFunctionLBoundFunctionLCaseFunctionLeftFunctionLenFunctionLengthPropertyLoadPictureFunctionLogFunctionLTrimFunctionMatchObjectMatchesCollectionMidFunctionMinuteFunctionMiscellaneousConstantsModOperatorMonthFunctionMonthNameFunction
MsgBoxConstantsMsgBoxFunctionMultiplicationOperator(*)NegationOperator(-)NotOperatorNowFunctionNothingNullNumberPropertyOctFunctionOnErrorStatementOperatorPrecedenceOptionExplicitStatementOrOperatorPatternPropertyPrivateStatementPropertyGetStatementPropertyLetStatementPropertySetStatementPublicStatementRaiseMethodRandomizeStatementReDimStatementRegExpObjectRemStatementReplaceFunctionReplaceMethodRGBFunctionRightFunctionRndFunctionRoundFunctionRTrimFunctionScriptEngineFunctionScriptEngineBuildVersionFunctionScriptEngineMajorVersionFunctionScriptEngineMinorVersionFunctionSecondFunction
SelectCaseStatementSetStatementSgnFunctionSinFunctionSourcePropertySpaceFunctionSplitFunctionSqrFunctionStrCompFunctionStringConstantsStringFunctionStrReverseFunctionSubStatementSubtractionOperator(-)TanFunctionTerminateEventTestMethodTimeFunctionTimerFunctionTimeSerialFunctionTimeValueFunctionTrimFunctionTristateConstantsTrueTypeNameFunctionUBoundFunctionUCaseFunctionValuePropertyVarTypeConstantsVarTypeFunctionVBScriptConstantsWeekdayFunctionWeekdayNameFunctionWhile...WendStatementWithStatementXorOperatorYearFunction
Microsoft®VisualBasic®ScriptingEdition
ConstantsVBScriptLanguageReference
VersionInformation
ColorConstantsComparisonConstantsDateandTimeConstantsDateFormatConstantsMiscellaneousConstantsMsgBoxConstantsStringConstantsTristateConstantsVarTypeConstantsVBScriptConstants
Microsoft®VisualBasic®ScriptingEdition
VBScriptErrorsVBScriptLanguageReference
VersionInformation
Run-timeErrorsSyntaxErrors
Microsoft®VisualBasic®ScriptingEdition
EventsVBScriptLanguageReference
VersionInformation
InitializeEventTerminateEvent
Microsoft®VisualBasic®Scripting
EditionFunctionsVBScriptLanguageReference
VersionInformation
AbsFunctionArrayFunctionAscFunctionAtnFunctionCBoolFunctionCByteFunctionCCurFunctionCDateFunctionCDblFunctionChrFunctionCIntFunctionCLngFunctionCosFunctionCreateObjectFunctionCSngFunctionCStrFunctionDateFunctionDateAddFunctionDateDiffFunctionDatePartFunctionDateSerialFunctionDateValueFunctionDayFunctionEvalFunctionExpFunctionFilterFunctionFixFunctionFormatCurrencyFunctionFormatDateTimeFunctionFormatNumberFunctionFormatPercentFunctionGetObjectFunction
GetRefFunctionHexFunctionHourFunctionInputBoxFunctionInStrFunctionInStrRevFunctionIntFunctionIsArrayFunctionIsDateFunctionIsEmptyFunctionIsNullFunctionIsNumericFunctionIsObjectFunctionJoinFunctionLBoundFunctionLCaseFunctionLeftFunctionLenFunctionLoadPictureFunctionLogFunctionLTrimFunctionMidFunctionMinuteFunctionMonthFunctionMonthNameFunctionMsgBoxFunctionNowFunctionOctFunctionReplaceFunctionRGBFunctionRightFunctionRndFunctionRoundFunctionRTrimFunctionScriptEngineFunctionScriptEngineBuildVersionFunctionScriptEngineMajorVersionFunction
ScriptEngineMinorVersionFunctionSecondFunctionSgnFunctionSinFunctionSpaceFunctionSplitFunctionSqrFunctionStrCompFunctionStringFunctionStrReverseFunctionTanFunctionTimeFunctionTimerFunctionTimeSerialFunctionTimeValueFunctionTrimFunctionTypeNameFunctionUBoundFunctionUCaseFunctionVarTypeFunctionWeekdayFunctionWeekdayNameFunctionYearFunction
Microsoft®VisualBasic®ScriptingEdition
MethodsVBScriptLanguageReference
VersionInformation
ClearMethodExecuteMethodRaiseMethodReplaceMethodTestMethod
Microsoft®VisualBasic®ScriptingEdition
ObjectsVBScriptLanguageReference
VersionInformation
ClassObjectDictionaryObjectErrObjectFileSystemObjectObjectMatchObjectMatchesCollectionRegExpObject
Microsoft®VisualBasic®ScriptingEdition
OperatorsVBScriptLanguageReference
VersionInformation
AdditionOperator(+)AndOperatorAssignmentOperator(=)ConcatenationOperator(&)DivisionOperator(/)EqvOperatorExponentiationOperator(^)ImpOperatorIntegerDivisionOperator(\)IsOperatorModOperatorMultiplicationOperator(*)NegationOperator(-)NotOperatorOperatorPrecedenceOrOperatorSubtractionOperator(-)XorOperator
Microsoft®VisualBasic®ScriptingEdition
PropertiesVBScriptLanguageReference
VersionInformation
DescriptionPropertyFirstIndexPropertyGlobalPropertyHelpContextPropertyHelpFilePropertyIgnoreCasePropertyLengthPropertyNumberPropertyPatternPropertySourcePropertyValueProperty
Microsoft®VisualBasic®Scripting
EditionStatementsVBScriptLanguageReference
VersionInformation
CallStatementClassStatementConstStatementDimStatementDo...LoopStatementEraseStatementExecuteStatementExitStatementFor...NextStatementForEach...NextStatementFunctionStatementIf...Then...ElseStatementOnErrorStatementOptionExplicitStatementPrivateStatementPropertyGetStatementPropertyLetStatementPropertySetStatementPublicStatementRandomizeStatementReDimStatementRemStatementSelectCaseStatementSetStatementSubStatementWhile...WendStatementWithStatement
Microsoft®VisualBasic®ScriptingEditionUsingConditionalStatements
VBScriptTutorialPrevious
Next
ControllingProgramExecution
Youcancontroltheflowofyourscriptwithconditionalstatementsandloopingstatements.Usingconditionalstatements,youcanwriteVBScriptcodethatmakesdecisionsandrepeatsactions.ThefollowingconditionalstatementsareavailableinVBScript:
If...Then...Elsestatement
SelectCasestatement
MakingDecisionsUsingIf...Then...Else
TheIf...Then...ElsestatementisusedtoevaluatewhetheraconditionisTrueorFalseand,dependingontheresult,tospecifyoneormorestatementstorun.Usuallytheconditionisanexpressionthatusesacomparisonoperatortocompareonevalueorvariablewithanother.Forinformationaboutcomparisonoperators,seeComparisonOperators.If...Then...Elsestatementscanbenestedtoasmanylevelsasyouneed.
RunningStatementsifaConditionisTrue
TorunonlyonestatementwhenaconditionisTrue,usethesingle-linesyntaxfortheIf...Then...Elsestatement.Thefollowingexampleshowsthesingle-linesyntax.NoticethatthisexampleomitstheElsekeyword.
SubFixDate()
DimmyDatemyDate=#2/13/95#IfmyDate<NowThenmyDate=NowEndSub
Torunmorethanonelineofcode,youmustusethemultiple-line(orblock)syntax.ThissyntaxincludestheEndIfstatement,asshowninthefollowingexample:
SubAlertUser(value)Ifvalue=0ThenAlertLabel.ForeColor=vbRedAlertLabel.Font.Bold=TrueAlertLabel.Font.Italic=TrueEndIfEndSub
RunningCertainStatementsifaConditionisTrueandRunningOthersifaConditionisFalse
YoucanuseanIf...Then...Elsestatementtodefinetwoblocksofexecutablestatements:oneblocktoruniftheconditionisTrue,theotherblocktoruniftheconditionisFalse.
SubAlertUser(value)Ifvalue=0ThenAlertLabel.ForeColor=vbRedAlertLabel.Font.Bold=TrueAlertLabel.Font.Italic=True
ElseAlertLabel.Forecolor=vbBlackAlertLabel.Font.Bold=FalseAlertLabel.Font.Italic=FalseEndIfEndSub
DecidingBetweenSeveralAlternatives
AvariationontheIf...Then...Elsestatementallowsyoutochoosefromseveralalternatives.AddingElseIfclausesexpandsthefunctionalityoftheIf...Then...Elsestatementsoyoucancontrolprogramflowbasedondifferentpossibilities.Forexample:
SubReportValue(value)Ifvalue=0ThenMsgBoxvalueElseIfvalue=1ThenMsgBoxvalueElseIfvalue=2thenMsgboxvalueElseMsgbox"Valueoutofrange!"EndIf
YoucanaddasmanyElseIfclausesasyouneedtoprovidealternativechoices.ExtensiveuseoftheElseIfclausesoftenbecomescumbersome.AbetterwaytochoosebetweenseveralalternativesistheSelectCasestatement.
MakingDecisionswithSelectCase
TheSelectCasestructureprovidesanalternativetoIf...Then...ElseIfforselectivelyexecutingoneblockofstatementsfromamongmultipleblocksofstatements.ASelectCasestatementprovidescapabilitysimilartotheIf...Then...Elsestatement,butitmakescodemoreefficientandreadable.
ASelectCasestructureworkswithasingletestexpressionthatisevaluatedonce,atthetopofthestructure.TheresultoftheexpressionisthencomparedwiththevaluesforeachCaseinthestructure.Ifthereisamatch,theblockofstatementsassociatedwiththatCaseisexecuted:
SelectCaseDocument.Form1.CardType.Options(SelectedIndex).TextCase"MasterCard"DisplayMCLogoValidateMCAccountCase"Visa"DisplayVisaLogoValidateVisaAccountCase"AmericanExpress"DisplayAMEXCOLogoValidateAMEXCOAccountCaseElseDisplayUnknownImagePromptAgainEndSelect
NoticethattheSelectCasestructureevaluatesanexpressiononceatthetopofthestructure.Incontrast,theIf...Then...ElseIfstructurecanevaluateadifferentexpressionforeachElseIfstatement.Youcanreplacean
If...Then...ElseIfstructurewithaSelectCasestructureonlyifeachElseIfstatementevaluatesthesameexpression.
Microsoft®VisualBasic®ScriptingEditionLoopingThroughCode
VBScriptTutorialPrevious
Next
UsingLoopstoRepeatCode
Loopingallowsyoutorunagroupofstatementsrepeatedly.SomeloopsrepeatstatementsuntilaconditionisFalse;othersrepeatstatementsuntilaconditionisTrue.Therearealsoloopsthatrepeatstatementsaspecificnumberoftimes.
ThefollowingloopingstatementsareavailableinVBScript:
Do...Loop:LoopswhileoruntilaconditionisTrue.
While...Wend:LoopswhileaconditionisTrue.
For...Next:Usesacountertorunstatementsaspecifiednumberoftimes.
ForEach...Next:Repeatsagroupofstatementsforeachiteminacollectionoreachelementofanarray.
UsingDoLoops
YoucanuseDo...Loopstatementstorunablockofstatementsanindefinitenumberoftimes.ThestatementsarerepeatedeitherwhileaconditionisTrueoruntilaconditionbecomesTrue.
RepeatingStatementsWhileaConditionisTrue
UsetheWhilekeywordtocheckaconditioninaDo...Loopstatement.Youcanchecktheconditionbeforeyouentertheloop(asshowninthefollowingChkFirstWhileexample),oryoucancheckitaftertheloophasrunatleastonce(asshownintheChkLastWhileexample).IntheChkFirstWhileprocedure,ifmyNumissetto9insteadof20,thestatementsinsidetheloopwillneverrun.IntheChkLastWhileprocedure,the
statementsinsidethelooprunonlyoncebecausetheconditionisalreadyFalse.
SubChkFirstWhile()Dimcounter,myNumcounter=0myNum=20DoWhilemyNum>10myNum=myNum-1counter=counter+1LoopMsgBox"Theloopmade"&counter&"repetitions."EndSub
SubChkLastWhile()Dimcounter,myNumcounter=0myNum=9DomyNum=myNum-1counter=counter+1LoopWhilemyNum>10MsgBox"Theloopmade"&counter&"repetitions."EndSub
RepeatingaStatementUntilaConditionBecomesTrue
YoucanusetheUntilkeywordintwowaystocheckaconditioninaDo...Loopstatement.Youcanchecktheconditionbeforeyouentertheloop(asshowninthefollowingChkFirstUntilexample),oryoucancheckitaftertheloophasrunatleastonce(asshownintheChkLastUntilexample).AslongastheconditionisFalse,theloopingoccurs.
SubChkFirstUntil()Dimcounter,myNum
counter=0myNum=20DoUntilmyNum=10myNum=myNum-1counter=counter+1LoopMsgBox"Theloopmade"&counter&"repetitions."EndSub
SubChkLastUntil()Dimcounter,myNumcounter=0myNum=1DomyNum=myNum+1counter=counter+1LoopUntilmyNum=10MsgBox"Theloopmade"&counter&"repetitions."EndSub
ExitingaDo...LoopStatementfromInsidetheLoop
YoucanexitaDo...LoopbyusingtheExitDostatement.Becauseyouusuallywanttoexitonlyincertainsituations,suchastoavoidanendlessloop,youshouldusetheExitDostatementintheTruestatementblockofanIf...Then...Elsestatement.IftheconditionisFalse,thelooprunsasusual.
Inthefollowingexample,myNumisassignedavaluethatcreatesanendlessloop.TheIf...Then...Elsestatementchecksforthiscondition,preventingtheendlessrepetition.
SubExitExample()Dimcounter,myNumcounter=0myNum=9
DoUntilmyNum=10myNum=myNum-1counter=counter+1IfmyNum<10ThenExitDoLoopMsgBox"Theloopmade"&counter&"repetitions."EndSub
UsingWhile...Wend
TheWhile...WendstatementisprovidedinVBScriptforthosewhoarefamiliarwithitsusage.However,becauseofthelackofflexibilityinWhile...Wend,itisrecommendedthatyouuseDo...Loopinstead.
UsingFor...Next
YoucanuseFor...Nextstatementstorunablockofstatementsaspecificnumberoftimes.Forloops,useacountervariablewhosevalueisincreasedordecreasedwitheachrepetitionoftheloop.
Forexample,thefollowingprocedurecausesaprocedurecalledMyProctoexecute50times.TheForstatementspecifiesthecountervariablexanditsstartandendvalues.TheNextstatementincrementsthecountervariableby1.
SubDoMyProc50Times()DimxForx=1To50MyProcNextEndSub
UsingtheStepkeyword,youcanincreaseordecreasethecountervariablebythevalueyouspecify.Inthefollowingexample,thecountervariablejisincrementedby2eachtimethelooprepeats.Whentheloopisfinished,totalisthesumof2,4,6,8,and10.
SubTwosTotal()
Dimj,totalForj=2To10Step2total=total+jNextMsgBox"Thetotalis"&totalEndSub
Todecreasethecountervariable,youuseanegativeStepvalue.Youmustspecifyanendvaluethatislessthanthestartvalue.Inthefollowingexample,thecountervariablemyNumisdecreasedby2eachtimethelooprepeats.Whentheloopisfinished,totalisthesumof16,14,12,10,8,6,4,and2.
SubNewTotal()DimmyNum,totalFormyNum=16To2Step-2total=total+myNumNextMsgBox"Thetotalis"&totalEndSub
YoucanexitanyFor...NextstatementbeforethecounterreachesitsendvaluebyusingtheExitForstatement.Becauseyouusuallywanttoexitonlyincertainsituations,suchaswhenanerroroccurs,youshouldusetheExitForstatementintheTruestatementblockofanIf...Then...Elsestatement.IftheconditionisFalse,thelooprunsasusual.
UsingForEach...Next
AForEach...NextloopissimilartoaFor...Nextloop.Insteadofrepeatingthestatementsaspecifiednumberoftimes,aForEach...Nextlooprepeatsagroupofstatementsforeachiteminacollectionofobjectsorforeachelementofanarray.Thisisespeciallyhelpfulifyoudon'tknowhowmanyelementsareinacollection.
InthefollowingHTMLcodeexample,thecontentsofaDictionaryobjectisusedtoplacetextinseveraltextboxes:
<HTML><HEAD><TITLE>FormsandElements</TITLE></HEAD><SCRIPTLANGUAGE="VBScript"><!--SubcmdChange_OnClickDimd'CreateavariableSetd=CreateObject("Scripting.Dictionary")d.Add"0","Athens"'Addsomekeysanditemsd.Add"1","Belgrade"d.Add"2","Cairo"
ForEachIindDocument.frmForm.Elements(I).Value=D.Item(I)NextEndSub--></SCRIPT><BODY><CENTER><FORMNAME="frmForm"
<InputType="Text"><p><InputType="Text"><p><InputType="Text"><p><InputType="Text"><p><InputType="Button"NAME="cmdChange"VALUE="ClickHere"><p></FORM></CENTER></BODY></HTML>
Microsoft®VisualBasic®ScriptingEdition
VBScriptandForms
VBScriptTutorialPrevious
Next
SimpleValidation
YoucanuseVisualBasicScriptingEditiontodomuchoftheformprocessingthatyou'dusuallyhavetodoonaserver.Youcanalsodothingsthatjustcan'tbedoneontheserver.
Here'sanexampleofsimpleclient-sidevalidation.TheHTMLcodeisforatextboxandabutton.IfyouuseMicrosoft®InternetExplorertoviewthepageproducedbythefollowingcode,you'llseeasmalltextboxwithabuttonnexttoit.
<HTML><HEAD><TITLE>SimpleValidation</TITLE><SCRIPTLANGUAGE="VBScript"><!--SubButton1_OnClickDimTheFormSetTheForm=Document.ValidFormIfIsNumeric(TheForm.Text1.Value)ThenIfTheForm.Text1.Value<1OrTheForm.Text1.Value>10ThenMsgBox"Pleaseenteranumberbetween1and10."ElseMsgBox"Thankyou."EndIfElse
MsgBox"Pleaseenteranumericvalue."EndIfEndSub--></SCRIPT></HEAD><BODY><H3>SimpleValidation</H3><HR><FORMNAME="ValidForm">Enteravaluebetween1and10:<INPUTNAME="Text1"TYPE="TEXT"SIZE="2"><INPUTNAME="Button1"TYPE="BUTTON"VALUE="Submit"></FORM></BODY></HTML>
ThedifferencebetweenthistextboxandtheexamplesonASimpleVBScriptPageisthattheValuepropertyofthetextboxisusedtochecktheenteredvalue.TogettheValueproperty,thecodehastoqualifythereferencetothenameofthetextbox.
YoucanalwayswriteoutthefullreferenceDocument.ValidForm.Text1.However,whereyouhavemultiplereferencestoformcontrols,you'llwanttodowhatwasdonehere.Firstdeclareavariable.ThenusetheSetstatementtoassigntheformtothevariableTheForm.Aregularassignmentstatement,suchasDim,doesn'tworkhere;youmustuseSettopreservethereferencetoanobject.
UsingNumericValues
Noticethattheexampledirectlyteststhevalueagainstanumber:itusestheIsNumericfunctiontomakesurethestringinthetextboxisanumber.AlthoughVBScriptautomaticallyconvertsstringsandnumbers,it'salways
agoodpracticetotestauser-enteredvalueforitsdatasubtypeandtouseconversionfunctionsasnecessary.Whendoingadditionwithtextboxvalues,convertthevaluesexplicitlytonumbersbecausetheplussign(+)operatorrepresentsbothadditionandstringconcatenation.Forexample,ifText1contains"1"andText2contains"2",youseethefollowingresults:
A=Text1.Value+Text2.Value 'Ais"12"A=CDbl(Text1.Value)+Text2.Value 'Ais3
ValidatingandPassingDataBacktotheServer
Thesimplevalidationexampleusesaplainbuttoncontrol.IfaSubmitcontrolwasused,theexamplewouldneverseethedatatocheckit—everythingwouldgoimmediatelytotheserver.AvoidingtheSubmitcontrolletsyoucheckthedata,butitdoesn'tsubmitthedatatotheserver.Thatrequiresanadditionallineofcode:
<SCRIPTLANGUAGE="VBScript"><!--SubButton1_OnClickDimTheFormSetTheForm=Document.ValidFormIfIsNumeric(TheForm.Text1.Value)ThenIfTheForm.Text1.Value<1OrTheForm.Text1.Value>10ThenMsgBox"Pleaseenteranumberbetween1and10."ElseMsgBox"Thankyou."TheForm.Submit 'Datacorrect;sendtoserver.EndIfElseMsgBox"Pleaseenteranumericvalue."EndIfEndSub-->
</SCRIPT>
Tosendthedatatotheserver,thecodeinvokestheSubmitmethodontheformobjectwhenthedataiscorrect.Fromthere,theserverhandlesthedatajustasitotherwisewould—exceptthatthedataiscorrectbeforeitgetsthere.FindcompleteinformationabouttheSubmitmethodandothermethodsintheInternetExplorerScriptingObjectModeldocumentation,whichcanbefoundontheMicrosoft®Website(http://www.microsoft.com).
Sofar,you'veseenonlythestandardHTML<FORM>objects.InternetExploreralsoletsyouexploitthefullpowerofActiveX®controls(formerlycalledOLEcontrols)andJava™objects.
tags">tags">
Microsoft®VisualBasic®ScriptingEditionUsingVBScriptwithObjects
VBScriptTutorialPrevious
UsingObjects
WhetheryouuseanActiveX®control(formerlycalledanOLEcontrol)oraJava™object,MicrosoftVisualBasicScriptingEditionandMicrosoft®InternetExplorerhandleitthesameway.Ifyou'reusingInternetExplorerandhaveinstalledtheLabelcontrol,youcanseethepageproducedbythefollowingcode.
Youincludeanobjectusingthe<OBJECT>tagsandsetitsinitialpropertyvaluesusing<PARAM>tags.Ifyou'reaVisualBasicprogrammer,you'llrecognizethatusingthe<PARAM>tagsisjustlikesettinginitialpropertiesforacontrolonaform.Forexample,thefollowingsetof<OBJECT>and<PARAM>tagsaddstheActiveXLabelcontroltoapage:
<OBJECT classid="clsid:99B42120-6EC7-11CF-A6C7-00AA00A47DD2" id=lblActiveLbl width=250 height=250 align=left hspace=20 vspace=0><PARAMNAME="Angle"VALUE="90">
<PARAMNAME="Alignment"VALUE="4"><PARAMNAME="BackStyle"VALUE="0"><PARAMNAME="Caption"VALUE="ASimpleDesultoryLabel"><PARAMNAME="FontName"VALUE="Verdana,Arial,Helvetica"><PARAMNAME="FontSize"VALUE="20"><PARAMNAME="FontBold"VALUE="1"><PARAMNAME="FrColor"VALUE="0"></OBJECT>
Youcangetproperties,setproperties,andinvokemethodsjustaswithanyoftheformcontrols.Thefollowingcode,forexample,includes<FORM>controlsyoucanusetomanipulatetwopropertiesoftheLabelcontrol:
<FORMNAME="LabelControls"><INPUTTYPE="TEXT"NAME="txtNewText"SIZE=25><INPUTTYPE="BUTTON"NAME="cmdChangeIt"VALUE="ChangeText"><INPUTTYPE="BUTTON"NAME="cmdRotate"VALUE="RotateLabel"></FORM>
Withtheformdefined,aneventprocedureforthecmdChangeItbuttonchangesthelabeltext:
<SCRIPTLANGUAGE="VBScript"><!--SubcmdChangeIt_onClick DimTheForm SetTheForm=Document.LabelControls lblActiveLbl.Caption=TheForm.txtNewText.Value
EndSub--></SCRIPT>
ThecodequalifiesreferencestocontrolsandvaluesinsidetheformsjustasintheSimpleValidationexample.
SeveralActiveXcontrolsareavailableforusewithInternetExplorer.Youcanfindcompleteinformationabouttheproperties,methods,andeventsthere,aswellastheclassidentifiers(CLSID)forthecontrolsontheMicrosoft®Website(http://www.microsoft.com).Youcanfindmoreinformationaboutthe<OBJECT>tagontheInternetExplorer4.0Author'sGuideandHTMLReferencepage.
NoteEarlierreleasesofInternetExplorerrequiredbraces({})aroundtheclassidattributeanddidnotconformtotheW3Cspecification.Usingbraceswiththecurrentreleasegeneratesa"Thispageusesanoutdatedversionofthe<OBJECT>tag"message.
Microsoft®VisualBasic®ScriptingEdition
ScriptingRun-TimeLibraryReference
LanguageReferenceVersionInformation
FeatureInformation
AlphabeticKeywordList
Constants
Methods
Objects
Properties
WelcometotheScriptingRun-TimeLibraryReference
ThesehandyblocksofinformationwillhelpyouexplorethemanydifferentpartsoftheScriptingRun-TimeLibrary.
You'llfindallthepartsoftheScriptingRun-TimeLibrarylistedalphabeticallyundertheAlphabeticKeywordList.Butifyouwanttoexaminejustonecategory,say,objects,eachlanguagecategoryhasitsown,morecompactsection.
How'sitwork?Clickononeoftheheadingstothelefttodisplayalistofitemscontainedinthatcategory.Fromthislist,selectthetopicthatyouwanttoview.Onceyou'veopenedthattopic,youcaneasilylinktootherrelatedsections.
So,goaheadandtakealook!Studysomestatements,mulloverthemethods,orfigureoutafewfunctions.You'llseejusthowversatiletheScriptingRun-TimeLibrarycanbe!
©1999MicrosoftCorporation.Allrightsreserved.
Microsoft®VisualBasic®ScriptingEdition
FeatureInformation
ScriptingRun-TimeLibraryReference
VersionInformation
MicrosoftScriptingRun-TimeFeatures
Microsoft®VisualBasic®ScriptingEdition
AlphabeticKeywordList
ScriptingRun-TimeLibraryReference
VersionInformation
AddMethod(Dictionary)AddMethod(Folders)AtEndOfLinePropertyAtEndOfStreamPropertyAttributesPropertyAvailableSpacePropertyBuildPathMethodCloseMethodColumnPropertyCompareModePropertyCopyMethodCopyFileMethodCopyFolderMethodCountPropertyCreateFolderMethodCreateTextFileMethodDateCreatedPropertyDateLastAccessedPropertyDateLastModifiedPropertyDeleteMethodDeleteFileMethodDeleteFolderMethodDictionaryObjectDriveObjectDrivePropertyDriveTypeConstantsDriveExistsMethodDriveLetterPropertyDrivesCollection
DrivesPropertyDriveTypePropertyExistsMethodFileExistsMethodFileAttributeConstantsFileInput/OutputConstantsFileObjectFilesCollectionFilesPropertyFileSystemObjectConstantsFileSystemObjectObjectFileSystemPropertyFolderObjectFoldersCollectionFolderExistsMethodFreeSpacePropertyGetAbsolutePathNameMethodGetBaseNameMethodGetDriveMethodGetDriveNameMethodGetExtensionNameMethodGetFileMethodGetFileNameMethodGetFileVersionMethodGetFolderMethodGetParentFolderNameMethodGetSpecialFolderMethodGetTempNameMethodIsReadyPropertyIsRootFolderPropertyItemPropertyItemsMethodKeyPropertyKeysMethodLinePropertyMoveMethodMoveFileMethod
MoveFolderMethodNamePropertyOpenAsTextStreamMethodOpenTextFileMethodParentFolderPropertyPathPropertyReadMethodReadAllMethodReadLineMethodRemoveMethodRemoveAllMethodRootFolderPropertySerialNumberPropertyShareNamePropertyShortNamePropertyShortPathPropertySizePropertySkipMethodSkipLineMethodSpecialFolderConstantsSubfoldersPropertyTextStreamObjectTotalSizePropertyTypePropertyVolumeNamePropertyWriteMethodWriteBlankLinesMethodWriteLineMethod
Microsoft®VisualBasic®ScriptingEdition
ConstantsScriptingRun-TimeLibrary
ReferenceVersionInformation
DriveTypeConstantsFileAttributeConstantsFileInput/OutputConstantsFileSystemObjectConstantsSpecialFolderConstants
Microsoft®VisualBasic®ScriptingEdition
MethodsScriptingRun-TimeLibrary
ReferenceVersionInformation
AddMethod(Dictionary)AddMethod(Folders)BuildPathMethodCloseMethodCopyMethodCopyFileMethodCopyFolderMethodCreateFolderMethodCreateTextFileMethodDeleteMethodDeleteFileMethodDeleteFolderMethodDriveExistsMethodExistsMethodFileExistsMethodFolderExistsMethodGetAbsolutePathNameMethodGetBaseNameMethodGetDriveMethodGetDriveNameMethodGetExtensionNameMethodGetFileMethodGetFileNameMethodGetFileVersionMethodGetFolderMethodGetParentFolderNameMethodGetSpecialFolderMethodGetTempNameMethodItemsMethodKeysMethod
MoveMethodMoveFileMethodMoveFolderMethodOpenAsTextStreamMethodOpenTextFileMethodReadMethodReadAllMethodReadLineMethodRemoveMethodRemoveAllMethodSkipMethodSkipLineMethodWriteMethodWriteBlankLinesMethodWriteLineMethod
Microsoft®VisualBasic®ScriptingEdition
ObjectsScriptingRun-TimeLibrary
ReferenceVersionInformation
DictionaryObjectDriveObjectDrivesCollectionFileObjectFilesCollectionFileSystemObjectObjectFolderObjectFoldersCollectionTextStreamObject
Microsoft®VisualBasic®ScriptingEdition
PropertiesScriptingRun-TimeLibrary
ReferenceVersionInformation
AtEndOfLinePropertyAtEndOfStreamPropertyAttributesPropertyAvailableSpacePropertyColumnPropertyCompareModePropertyCountPropertyDateCreatedPropertyDateLastAccessedPropertyDateLastModifiedPropertyDrivePropertyDriveLetterPropertyDrivesPropertyDriveTypePropertyFilesPropertyFileSystemPropertyFreeSpacePropertyIsReadyPropertyIsRootFolderPropertyItemPropertyKeyPropertyLinePropertyNamePropertyParentFolderPropertyPathPropertyRootFolderPropertySerialNumberPropertyShareNamePropertyShortNamePropertyShortPathProperty
SizePropertySubFoldersPropertyTotalSizePropertyTypePropertyVolumeNameProperty
Microsoft®ScriptingLibrary-FileSystemObjectTheFileSystemObjectObjectModel
Next
WhenwritingscriptsforActiveServerPages,theWindowsScriptingHost,orotherapplicationswherescriptingcanbeused,it'softenimportanttoadd,move,change,create,ordeletefolders(directories)andfilesontheWebserver.ItmayalsobenecessarytogetinformationaboutandmanipulatedrivesattachedtotheWebserver.
Scriptingallowsyoutoprocessdrives,folders,andfilesusingtheFileSystemObject(FSO)objectmodel,whichisexplainedinthefollowingsections:
IntroductiontotheFileSystemObjectandtheScriptingRun-TimeLibraryReference
FileSystemObjectObjects
ProgrammingtheFileSystemObject
WorkingwithDrivesandFolders
WorkingwithFiles
FileSystemObjectSampleCode
Microsoft®ScriptingLibrary-FileSystemObject
IntroductiontotheFileSystemObjectandtheScriptingRun-TimeLibraryReference
PreviousNext
TheFileSystemObject(FSO)objectmodelallowsyoutousethefamiliarobject.methodsyntaxwitharichsetofproperties,methods,andeventstoprocessfoldersandfiles.
Usethisobject-basedtoolwith:
HTMLtocreateWebpages
WindowsScriptingHosttocreatebatchfilesforMicrosoftWindows
ScriptControltoprovideascriptingcapabilitytoapplicationsdevelopedinotherlanguages
BecauseuseoftheFSOontheclientsideraisesserioussecurityissuesaboutprovidingpotentiallyunwelcomeaccesstoaclient'slocalfilesystem,thisdocumentationassumesuseoftheFSOobjectmodeltocreatescriptsexecutedbyInternetWebpagesontheserverside.Sincetheserversideisused,theInternetExplorerdefaultsecuritysettingsdonotallowclient-sideuseoftheFileSystemObjectobject.Overridingthosedefaultscouldsubjectalocalcomputertounwelcomeaccesstothefilesystem,whichcouldresultintotaldestructionofthefilesystem'sintegrity,causinglossofdata,orworse.
TheFSOobjectmodelgivesyourserver-sideapplicationstheabilitytocreate,alter,move,anddeletefolders,ortodetectifparticularfoldersexist,andifso,where.Youcanalsofindoutinformationabout
folders,suchastheirnames,thedatetheywerecreatedorlastmodified,andsoforth.
TheFSOobjectmodelalsomakesiteasytoprocessfiles.Whenprocessingfiles,theprimarygoalistostoredatainaspace-andresource-efficient,easy-to-accessformat.Youneedtobeabletocreatefiles,insertandchangethedata,andoutput(read)thedata.Sincestoringdatainadatabase,suchasAccessorSQLServer,addsasignificantamountofoverheadtoyourapplication,storingyourdatainabinaryortextfilemaybethemostefficientsolution.Youmayprefernottohavethisoverhead,oryourdataaccessrequirementsmaynotrequirealltheextrafeaturesassociatedwithafull-featureddatabase.
TheFSOobjectmodel,whichiscontainedintheScriptingtypelibrary(Scrrun.dll),supportstextfilecreationandmanipulationthroughtheTextStreamobject.Althoughitdoesnotyetsupportthecreationormanipulationofbinaryfiles,futuresupportofbinaryfilesisplanned.
Microsoft®ScriptingLibrary-FileSystemObject
FileSystemObjectObjects
PreviousNext
TheFileSystemObject(FSO)objectmodelcontainsthefollowingobjectsandcollections.
Object/Collection Description
FileSystemObject
Mainobject.Containsmethodsandpropertiesthatallowyoutocreate,delete,gaininformationabout,andgenerallymanipulatedrives,folders,andfiles.ManyofthemethodsassociatedwiththisobjectduplicatethoseinotherFSOobjects;theyareprovidedforconvenience.
Drive
Object.Containsmethodsandpropertiesthatallowyoutogatherinformationaboutadriveattachedtothesystem,suchasitssharenameandhowmuchroomisavailable.Notethata"drive"isn'tnecessarilyaharddisk,butcanbeaCD-ROMdrive,aRAMdisk,andsoforth.Adrivedoesn'tneedtobephysicallyattachedtothesystem;itcanbealsobelogicallyconnectedthroughanetwork.
Drives
Collection.Providesalistofthedrivesattachedtothesystem,eitherphysicallyorlogically.TheDrivescollectionincludesalldrives,regardlessoftype.Removable-mediadrivesneednothavemediainsertedforthemtoappearinthiscollection.
File
Object.Containsmethodsandpropertiesthatallowyoutocreate,delete,ormoveafile.
Alsoallowsyoutoquerythesystemforafilename,path,andvariousotherproperties.
Files Collection.Providesalistofallfilescontainedwithinafolder.
Folder
Object.Containsmethodsandpropertiesthatallowyoutocreate,delete,ormovefolders.Alsoallowsyoutoquerythesystemforfoldernames,paths,andvariousotherproperties.
Folders Collection.ProvidesalistofallthefolderswithinaFolder.
TextStream Object.Allowsyoutoreadandwritetextfiles.
Microsoft®ScriptingLibrary-FileSystemObject
ProgrammingtheFileSystemObject
PreviousNext
ToprogramwiththeFileSystemObject(FSO)objectmodel:
UsetheCreateObjectmethodtocreateaFileSystemObjectobject.
Usetheappropriatemethodonthenewlycreatedobject.
Accesstheobject'sproperties.
TheFSOobjectmodeliscontainedintheScriptingtypelibrary,whichislocatedintheScrrun.dllfile.Therefore,youmusthaveScrrun.dllintheappropriatesystemdirectoryonyourWebservertousetheFSOobjectmodel.
CreatingaFileSystemObjectObject
First,createaFileSystemObjectobjectbyusingtheCreateObjectmethod.InVBScript,usethefollowingcodetocreateaninstanceoftheFileSystemObject:
DimfsoSetfso=CreateObject("Scripting.FileSystemObject")
ThissamplecodedemonstrateshowtocreateaninstanceoftheFileSystemObject.
InJScript,usethiscodetodothesamething:
varfso;fso=newActiveXObject("Scripting.FileSystemObject");
Inbothoftheseexamples,ScriptingisthenameofthetypelibraryandFileSystemObjectisthenameoftheobjectthatyouwanttocreate.You
cancreateonlyoneinstanceoftheFileSystemObjectobject,regardlessofhowmanytimesyoutrytocreateanother.
UsingtheAppropriateMethod
Second,usetheappropriatemethodoftheFileSystemObjectobject.Forexample,tocreateanewobject,useeitherCreateTextFileorCreateFolder(theFSOobjectmodeldoesn'tsupportthecreationordeletionofdrives).
Todeleteobjects,usetheDeleteFileandDeleteFoldermethodsoftheFileSystemObjectobject,ortheDeletemethodoftheFileandFolderobjects.Youcanalsocopyandmovefilesandfolders,byusingtheappropriatemethods.
NoteSomefunctionalityintheFileSystemObjectobjectmodelisredundant.Forexample,youcancopyafileusingeithertheCopyFilemethodoftheFileSystemObjectobject,oryoucanusetheCopymethodoftheFileobject.Themethodsworkthesame;bothexisttoofferprogrammingflexibility.
AccessingExistingDrives,Files,andFolders
Togainaccesstoanexistingdrive,file,orfolder,usetheappropriate"get"methodoftheFileSystemObjectobject:
GetDrive
GetFolder
GetFile
TogainaccesstoanexistingfileinVBScript:
Dimfso,f1Setfso=CreateObject("Scripting.FileSystemObject")Setf1=fso.GetFile("c:\test.txt")
TodothesamethinginJScript,usethefollowingcode:
varfso,f1;fso=newActiveXObject("Scripting.FileSystemObject");f1=fso.GetFile("c:\\test.txt");
Donotusethe"get"methodsfornewlycreatedobjects,sincethe"create"functionsalreadyreturnahandletothatobject.Forexample,ifyoucreateanewfolderusingtheCreateFoldermethod,don'tusetheGetFoldermethodtoaccessitsproperties,suchasName,Path,Size,andsoforth.JustsetavariabletotheCreateFolderfunctiontogainahandletothenewlycreatedfolder,thenaccessitsproperties,methods,andevents.TodothisinVBScript,usethefollowingcode:
SubCreateFolderDimfso,fldrSetfso=CreateObject("Scripting.FileSystemObject")Setfldr=fso.CreateFolder("C:\MyTest")Response.Write"Createdfolder:"&fldr.NameEndSub
TosetavariabletotheCreateFolderfunctioninJScript,usethissyntax:
functionCreateFolder(){varfso,fldr;fso=newActiveXObject("Scripting.FileSystemObject");fldr=fso.CreateFolder("C:\\MyTest");Response.Write("Createdfolder:"+fldr.Name);}
AccessingtheObject'sProperties
Onceyouhaveahandletoanobject,youcanaccessitsproperties.Forexample,togetthenameofaparticularfolder,firstcreateaninstanceoftheobject,thengetahandletoitwiththeappropriatemethod(inthiscase,the
GetFoldermethod,sincethefolderalreadyexists).
UsethiscodetogetahandletotheGetFoldermethodinVBScript:
Setfldr=fso.GetFolder("c:\")
TodothesamethinginJScript,usethefollowingcode:
varfldr=fso.GetFolder("c:\\");
NowthatyouhaveahandletoaFolderobject,youcancheckitsNameproperty.UsethefollowingcodetocheckthisinVBScript:
Response.Write"Foldernameis:"&fldr.Name
TocheckaNamepropertyinJScript,usethissyntax:
Response.Write("Foldernameis:"+fldr.Name);
Tofindoutthelasttimeafilewasmodified,usethefollowingVBScriptsyntax:
Dimfso,f1Setfso=CreateObject("Scripting.FileSystemObject")'GetaFileobjecttoquery.Setf1=fso.GetFile("c:\detlog.txt")'Printinformation.Response.Write"Filelastmodified:"&f1.DateLastModified
TofindoutthesamethinginJScript,usethiscode:
varfso,f1;fso=newActiveXObject("Scripting.FileSystemObject");//GetaFileobjecttoquery.f1=fso.GetFile("c:\\detlog.txt");//Printinformation.Response.Write("Filelastmodified:"+f1.DateLastModified);
Microsoft®ScriptingLibrary-FileSystemObject
WorkingwithDrivesandFolders
PreviousNext
WiththeFileSystemObject(FSO)objectmodel,youcanworkwithdrivesandfoldersprogrammaticallyjustasyoucanintheWindowsExplorerinteractively.Youcancopyandmovefolders,getinformationaboutdrivesandfolders,andsoforth.
GettingInformationAboutDrives
TheDriveobjectallowsyoutogaininformationaboutthevariousdrivesattachedtoasystem,eitherphysicallyoroveranetwork.Itspropertiesallowyoutoobtaininformationabout:
Thetotalsizeofthedriveinbytes(TotalSizeproperty)
Howmuchspaceisavailableonthedriveinbytes(AvailableSpaceorFreeSpaceproperties)
Whatletterisassignedtothedrive(DriveLetterproperty)
Whattypeofdriveitis,suchasremovable,fixed,network,CD-ROM,orRAMdisk(DriveTypeproperty)
Thedrive'sserialnumber(SerialNumberproperty)
Thetypeoffilesystemthedriveuses,suchasFAT,FAT32,NTFS,andsoforth(FileSystemproperty)
Whetheradriveisavailableforuse(IsReadyproperty)
Thenameoftheshareand/orvolume(ShareNameandVolumeNameproperties)
Thepathorrootfolderofthedrive(PathandRootFolderproperties)
Viewthesamplecodetoseehowthesepropertiesareusedin
FileSystemObject.
ExampleUsageoftheDriveObject
UsetheDriveobjecttogatherinformationaboutadrive.Youwon'tseeareferencetoanactualDriveobjectinthefollowingcode;instead,usetheGetDrivemethodtogetareferencetoanexistingDriveobject(inthiscase,drv).
ThefollowingexampledemonstrateshowtousetheDriveobjectinVBScript:
SubShowDriveInfo(drvPath)Dimfso,drv,sSetfso=CreateObject("Scripting.FileSystemObject")Setdrv=fso.GetDrive(fso.GetDriveName(drvPath))s="Drive"&UCase(drvPath)&"-"s=s&drv.VolumeName&"<br>"s=s&"TotalSpace:"&FormatNumber(drv.TotalSize/1024,0)s=s&"Kb"&"<br>"s=s&"FreeSpace:"&FormatNumber(drv.FreeSpace/1024,0)s=s&"Kb"&"<br>"Response.WritesEndSub
ThefollowingcodeillustratesthesamefunctionalityinJScript:
functionShowDriveInfo1(drvPath){varfso,drv,s="";fso=newActiveXObject("Scripting.FileSystemObject");drv=fso.GetDrive(fso.GetDriveName(drvPath));s+="Drive"+drvPath.toUpperCase()+"-";s+=drv.VolumeName+"<br>";s+="TotalSpace:"+drv.TotalSize/1024;s+="Kb"+"<br>";s+="FreeSpace:"+drv.FreeSpace/1024;
s+="Kb"+"<br>";Response.Write(s);}
WorkingwithFolders
Commonfoldertasksandthemethodsforperformingthemaredescribedinthefollowingtable.
Task MethodCreateafolder. FileSystemObject.CreateFolder
Deleteafolder. Folder.DeleteorFileSystemObject.DeleteFolder
Moveafolder. Folder.MoveorFileSystemObject.MoveFolder
Copyafolder. Folder.CopyorFileSystemObject.CopyFolder
Retrievethenameofafolder. Folder.Name
Findoutifafolderexistsonadrive. FileSystemObject.FolderExists
GetaninstanceofanexistingFolderobject.
FileSystemObject.GetFolder
Findoutthenameofafolder'sparentfolder.
FileSystemObject.GetParentFolderName
Findoutthepathofsystemfolders. FileSystemObject.GetSpecialFolder
ViewthesamplecodetoseehowmanyofthesemethodsandpropertiesareusedinFileSystemObject.
ThefollowingexampledemonstrateshowtousetheFolderandFileSystemObjectobjectstomanipulatefoldersandgaininformationabouttheminVBScript:
SubShowFolderInfo()Dimfso,fldr,s'GetinstanceofFileSystemObject.Setfso=CreateObject("Scripting.FileSystemObject")'GetDriveobject.Setfldr=fso.GetFolder("c:")'Printparentfoldername.Response.Write"Parentfoldernameis:"&fldr&"<br>"'Printdrivename.Response.Write"Containedondrive"&fldr.Drive&"<br>"'Printrootfilename.Iffldr.IsRootFolder=TrueThenResponse.Write"Thisistherootfolder."&""<br>"<br>"ElseResponse.Write"Thisfolderisn'tarootfolder."&"<br><br>"EndIf'CreateanewfolderwiththeFileSystemObjectobject.fso.CreateFolder("C:\Bogus")Response.Write"CreatedfolderC:\Bogus"&"<br>"'Printthebasenameofthefolder.Response.Write"Basename="&fso.GetBaseName("c:\bogus")&"<br>"'Deletethenewlycreatedfolder.fso.DeleteFolder("C:\Bogus")Response.Write"DeletedfolderC:\Bogus"&"<br>"EndSub
ThisexampleshowshowtousetheFolderandFileSystemObjectobjectsinJScript:
functionShowFolderInfo(){varfso,fldr,s="";//GetinstanceofFileSystemObject.fso=newActiveXObject("Scripting.FileSystemObject");
//GetDriveobject.fldr=fso.GetFolder("c:");//Printparentfoldername.Response.Write("Parentfoldernameis:"+fldr+"<br>");//Printdrivename.Response.Write("Containedondrive"+fldr.Drive+"<br>");//Printrootfilename.if(fldr.IsRootFolder)Response.Write("Thisistherootfolder.");elseResponse.Write("Thisfolderisn'tarootfolder.");Response.Write("<br><br>");//CreateanewfolderwiththeFileSystemObjectobject.fso.CreateFolder("C:\\Bogus");Response.Write("CreatedfolderC:\\Bogus"+"<br>");//Printthebasenameofthefolder.Response.Write("Basename="+fso.GetBaseName("c:\\bogus")+"<br>");//Deletethenewlycreatedfolder.fso.DeleteFolder("C:\\Bogus");Response.Write("DeletedfolderC:\\Bogus"+"<br>");}
Microsoft®ScriptingLibrary-FileSystemObject
WorkingwithFilesPrevious
Next
Therearetwomajorcategoriesoffilemanipulation:
Creating,adding,orremovingdata,andreadingfiles
Moving,copying,anddeletingfiles
CreatingFiles
Therearethreewaystocreateanemptytextfile(sometimesreferredtoasa"textstream").
ThefirstwayistousetheCreateTextFilemethod.ThefollowingexampledemonstrateshowtocreateatextfileusingthismethodinVBScript:
Dimfso,f1Setfso=CreateObject("Scripting.FileSystemObject")Setf1=fso.CreateTextFile("c:\testfile.txt",True)
TousethismethodinJScript,usethiscode:
varfso,f1;fso=newActiveXObject("Scripting.FileSystemObject");f1=fso.CreateTextFile("c:\\testfile.txt",true);
ViewthissamplecodetoseehowtheCreateTextFilemethodisusedinFileSystemObject.
ThesecondwaytocreateatextfileistousetheOpenTextFilemethodoftheFileSystemObjectobjectwiththeForWritingflagset.InVBScript,thecodelookslikethisexample:
Dimfso,tsConstForWriting=2Setfso=CreateObject("Scripting.FileSystemObject")Setts=fso.OpenTextFile("c:\test.txt",ForWriting,True)
TocreateatextfileusingthismethodinJScript,usethiscode:
varfso,ts;varForWriting=2;fso=newActiveXObject("Scripting.FileSystemObject");ts=fso.OpenTextFile("c:\\test.txt",ForWriting,true);
AthirdwaytocreateatextfileistousetheOpenAsTextStreammethodwiththeForWritingflagset.Forthismethod,usethefollowingcodeinVBScript:
Dimfso,f1,tsConstForWriting=2Setfso=CreateObject("Scripting.FileSystemObject")fso.CreateTextFile("c:\test1.txt")Setf1=fso.GetFile("c:\test1.txt")Setts=f1.OpenAsTextStream(ForWriting,True)
InJScript,usethecodeinthefollowingexample:
varfso,f1,ts;varForWriting=2;fso=newActiveXObject("Scripting.FileSystemObject");fso.CreateTextFile("c:\\test1.txt");f1=fso.GetFile("c:\\test1.txt");ts=f1.OpenAsTextStream(ForWriting,true);
AddingDatatotheFile
Oncethetextfileiscreated,adddatatothefileusingthefollowingthreesteps:
1. Openthetextfile.
2. Writethedata.
3. Closethefile.
Toopenanexistingfile,useeithertheOpenTextFilemethodoftheFileSystemObjectobjectortheOpenAsTextStreammethodoftheFileobject.
Towritedatatotheopentextfile,usetheWrite,WriteLine,orWriteBlankLinesmethodsoftheTextStreamobject,accordingtothetasksoutlinedinthefollowingtable.
Task MethodWritedatatoanopentextfilewithoutatrailingnewlinecharacter. Write
Writedatatoanopentextfilewithatrailingnewlinecharacter. WriteLine
Writeoneormoreblanklinestoanopentextfile. WriteBlankLines
ViewthissamplecodetoseehowtheWrite,WriteLine,andWriteBlankLinesmethodsareusedinFileSystemObject.
Tocloseanopenfile,usetheClosemethodoftheTextStreamobject.
ViewthissamplecodetoseehowtheClosemethodisusedinFileSystemObject.
NoteThenewlinecharactercontainsacharacterorcharacters(dependingontheoperatingsystem)toadvancethecursortothebeginningofthenextline(carriagereturn/linefeed).Beawarethattheendofsomestringsmayalreadyhavesuchnonprintingcharacters.
ThefollowingVBScriptexampledemonstrateshowtoopenafile,useallthreewritemethodstoadddatatothefile,andthenclosethefile:
SubCreateFile()Dimfso,tfSetfso=CreateObject("Scripting.FileSystemObject")Settf=fso.CreateTextFile("c:\testfile.txt",True)'Writealinewithanewlinecharacter.tf.WriteLine("Testing1,2,3.")
'Writethreenewlinecharacterstothefile.tf.WriteBlankLines(3)'Writealine.tf.Write("Thisisatest.")tf.CloseEndSub
ThisexampledemonstrateshowtousethethreemethodsinJScript:
functionCreateFile(){varfso,tf;fso=newActiveXObject("Scripting.FileSystemObject");tf=fso.CreateTextFile("c:\\testfile.txt",true);//Writealinewithanewlinecharacter.tf.WriteLine("Testing1,2,3.");//Writethreenewlinecharacterstothefile.tf.WriteBlankLines(3);//Writealine.tf.Write("Thisisatest.");tf.Close();}
ReadingFiles
Toreaddatafromatextfile,usetheRead,ReadLine,orReadAllmethodoftheTextStreamobject.Thefollowingtabledescribeswhichmethodtouseforvarioustasks.
Task MethodReadaspecifiednumberofcharactersfromafile. ReadReadanentireline(upto,butnotincluding,thenewlinecharacter). ReadLine
Readtheentirecontentsofatextfile. ReadAll
ViewthissamplecodetoseehowtheReadAllandReadLinemethodsareusedinFileSystemObject.
IfyouusetheReadorReadLinemethodandwanttoskiptoaparticularportionofdata,usetheSkiporSkipLinemethod.Theresultingtextofthereadmethodsisstoredinastringwhichcanbedisplayedinacontrol,parsedbystringfunctions(suchasLeft,Right,andMid),concatenated,andsoforth.
ThefollowingVBScriptexampledemonstrateshowtoopenafile,writetoit,andthenreadfromit:
SubReadFilesDimfso,f1,ts,sConstForReading=1Setfso=CreateObject("Scripting.FileSystemObject")Setf1=fso.CreateTextFile("c:\testfile.txt",True)'Writealine.Response.Write"Writingfile<br>"f1.WriteLine"HelloWorld"f1.WriteBlankLines(1)f1.Close'Readthecontentsofthefile.Response.Write"Readingfile<br>"Setts=fso.OpenTextFile("c:\testfile.txt",ForReading)s=ts.ReadLineResponse.Write"Filecontents='"&s&"'"ts.CloseEndSub
ThiscodedemonstratesthesamethinginJScript:
functionReadFiles(){varfso,f1,ts,s;varForReading=1;fso=newActiveXObject("Scripting.FileSystemObject");f1=fso.CreateTextFile("c:\\testfile.txt",true);//Writealine.
Response.Write("Writingfile<br>");f1.WriteLine("HelloWorld");f1.WriteBlankLines(1);f1.Close();//Readthecontentsofthefile.Response.Write("Readingfile<br>");ts=fso.OpenTextFile("c:\\testfile.txt",ForReading);s=ts.ReadLine();Response.Write("Filecontents='"+s+"'");ts.Close();}
Moving,Copying,andDeletingFiles
TheFSOobjectmodelhastwomethodseachformoving,copying,anddeletingfiles,asdescribedinthefollowingtable.
Task MethodMoveafile File.MoveorFileSystemObject.MoveFileCopyafile File.CopyorFileSystemObject.CopyFileDeleteafile File.DeleteorFileSystemObject.DeleteFile
ViewthissamplecodetoseetwowaystodeleteafileinFileSystemObject.
ThefollowingVBScriptexamplecreatesatextfileintherootdirectoryofdriveC,writessomeinformationtoit,movesittoadirectorycalled\tmp,makesacopyofitinadirectorycalled\temp,thendeletesthecopiesfrombothdirectories.
Torunthefollowingexample,createdirectoriesnamed\tmpand\tempintherootdirectoryofdriveC:
SubManipFilesDimfso,f1,f2,sSetfso=CreateObject("Scripting.FileSystemObject")Setf1=fso.CreateTextFile("c:\testfile.txt",True)Response.Write"Writingfile<br>"'Writealine.
f1.Write("Thisisatest.")'Closethefiletowriting.f1.CloseResponse.Write"Movingfiletoc:\tmp<br>"'GetahandletothefileinrootofC:\.Setf2=fso.GetFile("c:\testfile.txt")'Movethefileto\tmpdirectory.f2.Move("c:\tmp\testfile.txt")Response.Write"Copyingfiletoc:\temp<br>"'Copythefileto\temp.f2.Copy("c:\temp\testfile.txt")Response.Write"Deletingfiles<br>"'Gethandlestofiles'currentlocation.Setf2=fso.GetFile("c:\tmp\testfile.txt")Setf3=fso.GetFile("c:\temp\testfile.txt")'Deletethefiles.f2.Deletef3.DeleteResponse.Write"Alldone!"EndSub
ThiscodeshowsthesamethinginJScript:
functionManipFiles(){varfso,f1,f2,s;fso=newActiveXObject("Scripting.FileSystemObject");f1=fso.CreateTextFile("c:\\testfile.txt",true);Response.Write("Writingfile<br>");//Writealine.f1.Write("Thisisatest.");//Closethefiletowriting.f1.Close();
Response.Write("Movingfiletoc:\\tmp<br>");//GetahandletothefileinrootofC:\.f2=fso.GetFile("c:\\testfile.txt");//Movethefileto\tmpdirectory.f2.Move("c:\\tmp\\testfile.txt");Response.Write("Copyingfiletoc:\\temp<br>");//Copythefileto\temp.f2.Copy("c:\\temp\\testfile.txt");Response.Write("Deletingfiles<br>");//Gethandlestofiles'currentlocation.f2=fso.GetFile("c:\\tmp\\testfile.txt");f3=fso.GetFile("c:\\temp\\testfile.txt");//Deletethefiles.f2.Delete();f3.Delete();Response.Write("Alldone!");}
Microsoft®ScriptingLibrary-FileSystemObject
FileSystemObjectSampleCode
Previous
Thesamplecodedescribedinthissectionprovidesareal-worldexamplethatdemonstratesmanyofthefeaturesavailableintheFileSystemObjectobjectmodel.Thiscodeshowshowallthefeaturesoftheobjectmodelworktogether,andhowtousethosefeatureseffectivelyinyourowncode.
Notethatsincethiscodeisfairlygeneric,someadditionalcodeandalittletweakingareneededtomakethiscodeactuallyrunonyourmachine.ThesechangesarenecessarybecauseofthedifferentwaysinputandoutputtotheuserishandledbetweenActiveServerPagesandtheWindowsScriptingHost.
TorunthiscodeonanActiveServerPage,usethefollowingsteps:
1. CreateastandardWebpagewithan.aspextension.
2. Copythefollowingsamplecodeintothatfilebetweenthe<BODY;>...</BODY>tags.
3. Encloseallthecodewithin<%...%>tags.
4. MovetheOptionExplicitstatementfromitscurrentpositioninthecodetotheverytopofyourHTMLpage,positioningitevenbeforetheopening<HTML>tag.
5. Place<%...%>tagsaroundtheOptionExplicitstatementtoensurethatit'srunontheserverside.
6. Addthefollowingcodetotheendofthesamplecode:
SubPrint(x)Response.Write"<PRE><FONT;FACE=""CourierNew""SIZE=""1"">"Response.WritexResponse.Write"</FONT></PRE>"EndSubMain
Thepreviouscodeaddsaprintprocedurethatwillrunontheserverside,
butdisplayresultsontheclientside.TorunthiscodeontheWindowsScriptingHost,addthefollowingcodetotheendofthesamplecode:
SubPrint(x) WScript.EchoxEndSubMain
Thecodeiscontainedinthefollowingsection:
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''FileSystemObjectSampleCode''Copyright1998MicrosoftCorporation.AllRightsReserved.'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
OptionExplicit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Regardingcodequality:''1)Thefollowingcodedoesalotofstringmanipulationbyconcatenatingshort'stringstogetherwiththe"&"operator.Sincestringconcatenation'isexpensive,thisisaveryinefficientwaytowritecode.However,itisavery'maintainablewaytowritecode,andisusedherebecausethisprogramperformsextensive'diskoperations,andbecausethediskismuchslowerthanthememoryoperationsrequiredto'concatenatethestrings.Keepinmindthatthisisdemonstrationcode,notproductioncode.''2)"OptionExplicit"isused,becausedeclaredvariableaccessisslightlyfasterthan'undeclaredvariableaccess.Italsopreventsbugsfromcreepingintoyourcode,suchas'whenyoumisspellDriveTypeCDROMasDriveTypeCDORM.''3)Errorhandlingisabsentfromthiscode,tomakethecodemorereadable.Although'precautionshavebeentakentoensurethatthecodewillnoterrorincommoncases,file'systemscanbeunpredictable.Inproductioncode,useOnErrorResumeNextandthe'Errobjecttotrappossibleerrors.'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Somehandyglobalvariables'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
DimTabStopDimNewLine
ConstTestDrive="C"ConstTestFilePath="C:\Test"
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''ConstantsreturnedbyDrive.DriveType'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
ConstDriveTypeRemovable=1ConstDriveTypeFixed=2ConstDriveTypeNetwork=3ConstDriveTypeCDROM=4ConstDriveTypeRAMDisk=5
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''ConstantsreturnedbyFile.Attributes'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
ConstFileAttrNormal=0ConstFileAttrReadOnly=1ConstFileAttrHidden=2ConstFileAttrSystem=4ConstFileAttrVolume=8ConstFileAttrDirectory=16ConstFileAttrArchive=32ConstFileAttrAlias=64ConstFileAttrCompressed=128
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Constantsforopeningfiles'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
ConstOpenFileForReading=1ConstOpenFileForWriting=2ConstOpenFileForAppending=8
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''ShowDriveType'
'Purpose:''GeneratesastringdescribingthedrivetypeofagivenDriveobject.''Demonstratesthefollowing''-Drive.DriveType'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
FunctionShowDriveType(Drive)
DimS SelectCaseDrive.DriveType CaseDriveTypeRemovable S="Removable" CaseDriveTypeFixed S="Fixed" CaseDriveTypeNetwork S="Network" CaseDriveTypeCDROM S="CD-ROM" CaseDriveTypeRAMDisk S="RAMDisk" CaseElse S="Unknown" EndSelect
ShowDriveType=S
EndFunction
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''ShowFileAttr''Purpose:''Generatesastringdescribingtheattributesofafileorfolder.''Demonstratesthefollowing''-File.Attributes'-Folder.Attributes'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
FunctionShowFileAttr(File)'Filecanbeafileorfolder
DimS DimAttr Attr=File.Attributes
IfAttr=0Then ShowFileAttr="Normal" ExitFunction EndIf
IfAttrAndFileAttrDirectoryThenS=S&"Directory" IfAttrAndFileAttrReadOnlyThenS=S&"Read-Only" IfAttrAndFileAttrHiddenThenS=S&"Hidden" IfAttrAndFileAttrSystemThenS=S&"System" IfAttrAndFileAttrVolumeThenS=S&"Volume" IfAttrAndFileAttrArchiveThenS=S&"Archive" IfAttrAndFileAttrAliasThenS=S&"Alias" IfAttrAndFileAttrCompressedThenS=S&"Compressed"
ShowFileAttr=S
EndFunction
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''GenerateDriveInformation''Purpose:''Generatesastringdescribingthecurrentstateoftheavailabledrives.''Demonstratesthefollowing''-FileSystemObject.Drives'-IteratingtheDrivescollection'-Drives.Count'-Drive.AvailableSpace'-Drive.DriveLetter'-Drive.DriveType'-Drive.FileSystem'-Drive.FreeSpace'-Drive.IsReady'-Drive.Path'-Drive.SerialNumber'-Drive.ShareName'-Drive.TotalSize'-Drive.VolumeName'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
FunctionGenerateDriveInformation(FSO)
DimDrives DimDrive DimS
SetDrives=FSO.Drives
S="Numberofdrives:"&TabStop&Drives.Count&NewLine&NewLine
'Construct1stlineofreport. S=S&String(2,TabStop)&"Drive" S=S&String(3,TabStop)&"File" S=S&TabStop&"Total" S=S&TabStop&"Free" S=S&TabStop&"Available" S=S&TabStop&"Serial"&NewLine
'Construct2ndlineofreport. S=S&"Letter" S=S&TabStop&"Path" S=S&TabStop&"Type" S=S&TabStop&"Ready?" S=S&TabStop&"Name" S=S&TabStop&"System" S=S&TabStop&"Space" S=S&TabStop&"Space" S=S&TabStop&"Space" S=S&TabStop&"Number"&NewLine
'Separatorline. S=S&String(105,"-")&NewLine
ForEachDriveInDrives
S=S&Drive.DriveLetter S=S&TabStop&Drive.Path S=S&TabStop&ShowDriveType(Drive) S=S&TabStop&Drive.IsReady
IfDrive.IsReadyThen IfDriveTypeNetwork=Drive.DriveTypeThen S=S&TabStop&Drive.ShareName Else S=S&TabStop&Drive.VolumeName EndIf
S=S&TabStop&Drive.FileSystem S=S&TabStop&Drive.TotalSize
S=S&TabStop&Drive.FreeSpace S=S&TabStop&Drive.AvailableSpace S=S&TabStop&Hex(Drive.SerialNumber)
EndIf
S=S&NewLine
Next GenerateDriveInformation=S
EndFunction
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''GenerateFileInformation''Purpose:''Generatesastringdescribingthecurrentstateofafile.''Demonstratesthefollowing''-File.Path'-File.Name'-File.Type'-File.DateCreated'-File.DateLastAccessed'-File.DateLastModified'-File.Size'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
FunctionGenerateFileInformation(File)
DimS
S=NewLine&"Path:"&TabStop&File.Path S=S&NewLine&"Name:"&TabStop&File.Name S=S&NewLine&"Type:"&TabStop&File.Type S=S&NewLine&"Attribs:"&TabStop&ShowFileAttr(File) S=S&NewLine&"Created:"&TabStop&File.DateCreated S=S&NewLine&"Accessed:"&TabStop&File.DateLastAccessed S=S&NewLine&"Modified:"&TabStop&File.DateLastModified S=S&NewLine&"Size"&TabStop&File.Size&NewLine
GenerateFileInformation=S
EndFunction
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''GenerateFolderInformation''Purpose:''Generatesastringdescribingthecurrentstateofafolder.''Demonstratesthefollowing''-Folder.Path'-Folder.Name'-Folder.DateCreated'-Folder.DateLastAccessed'-Folder.DateLastModified'-Folder.Size'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
FunctionGenerateFolderInformation(Folder)
DimS
S="Path:"&TabStop&Folder.Path S=S&NewLine&"Name:"&TabStop&Folder.Name S=S&NewLine&"Attribs:"&TabStop&ShowFileAttr(Folder) S=S&NewLine&"Created:"&TabStop&Folder.DateCreated S=S&NewLine&"Accessed:"&TabStop&Folder.DateLastAccessed S=S&NewLine&"Modified:"&TabStop&Folder.DateLastModified S=S&NewLine&"Size:"&TabStop&Folder.Size&NewLine
GenerateFolderInformation=S
EndFunction
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''GenerateAllFolderInformation''Purpose:''Generatesastringdescribingthecurrentstateofa'folderandallfilesandsubfolders.''Demonstratesthefollowing''-Folder.Path'-Folder.SubFolders
'-Folders.Count'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
FunctionGenerateAllFolderInformation(Folder)
DimS DimSubFolders DimSubFolder DimFiles DimFile
S="Folder:"&TabStop&Folder.Path&NewLine&NewLine
SetFiles=Folder.Files
If1=Files.CountThen S=S&"Thereis1file"&NewLine Else S=S&"Thereare"&Files.Count&"files"&NewLine EndIf
IfFiles.Count<>0Then
ForEachFileInFiles S=S&GenerateFileInformation(File) Next
EndIf
SetSubFolders=Folder.SubFolders
If1=SubFolders.CountThen S=S&NewLine&"Thereis1subfolder"&NewLine&NewLine Else S=S&NewLine&"Thereare"&SubFolders.Count&"subfolders"&NewLine&NewLine EndIf
IfSubFolders.Count<>0Then
ForEachSubFolderInSubFolders S=S&GenerateFolderInformation(SubFolder) Next
S=S&NewLine
ForEachSubFolderInSubFolders S=S&GenerateAllFolderInformation(SubFolder) Next
EndIf
GenerateAllFolderInformation=S
EndFunction
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''GenerateTestInformation''Purpose:''GeneratesastringdescribingthecurrentstateoftheC:\Test'folderandallfilesandsubfolders.''Demonstratesthefollowing''-FileSystemObject.DriveExists'-FileSystemObject.FolderExists'-FileSystemObject.GetFolder'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
FunctionGenerateTestInformation(FSO)
DimTestFolder DimS
IfNotFSO.DriveExists(TestDrive)ThenExitFunction IfNotFSO.FolderExists(TestFilePath)ThenExitFunction
SetTestFolder=FSO.GetFolder(TestFilePath)
GenerateTestInformation=GenerateAllFolderInformation(TestFolder)
EndFunction
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''DeleteTestDirectory''Purpose:''Cleansupthetestdirectory.''Demonstratesthefollowing''-FileSystemObject.GetFolder'-FileSystemObject.DeleteFile
'-FileSystemObject.DeleteFolder'-Folder.Delete'-File.Delete'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
SubDeleteTestDirectory(FSO)
DimTestFolder DimSubFolder DimFile 'Twowaystodeleteafile:
FSO.DeleteFile(TestFilePath&"\Beatles\OctopusGarden.txt")
SetFile=FSO.GetFile(TestFilePath&"\Beatles\BathroomWindow.txt") File.Delete
'Twowaystodeleteafolder:
FSO.DeleteFolder(TestFilePath&"\Beatles")
FSO.DeleteFile(TestFilePath&"\ReadMe.txt")
SetTestFolder=FSO.GetFolder(TestFilePath) TestFolder.Delete
EndSub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''CreateLyrics''Purpose:''Buildsacoupleoftextfilesinafolder.'''Demonstratesthefollowing''-FileSystemObject.CreateTextFile'-TextStream.WriteLine'-TextStream.Write'-TextStream.WriteBlankLines'-TextStream.Close'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
SubCreateLyrics(Folder)
DimTextStream SetTextStream=Folder.CreateTextFile("OctopusGarden.txt") TextStream.Write("Octopus'Garden")'Notethatthisdoesnotaddalinefeedtothefile. TextStream.WriteLine("(byRingoStarr)") TextStream.WriteBlankLines(1) TextStream.WriteLine("I'dliketobeundertheseainanoctopus'gardenintheshade,") TextStream.WriteLine("He'dletusin,knowswherewe'vebeen--inhisoctopus'gardenintheshade.") TextStream.WriteBlankLines(2) TextStream.Close
SetTextStream=Folder.CreateTextFile("BathroomWindow.txt") TextStream.WriteLine("SheCameInThroughTheBathroomWindow(byLennon/McCartney)") TextStream.WriteLine("") TextStream.WriteLine("Shecameinthroughthebathroomwindowprotectedbyasilverspoon") TextStream.WriteLine("Butnowshesucksherthumbandwandersbythebanksofherownlagoon") TextStream.WriteBlankLines(2) TextStream.Close
EndSub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''GetLyrics''Purpose:''Displaysthecontentsofthelyricsfiles.'''Demonstratesthefollowing''-FileSystemObject.OpenTextFile'-FileSystemObject.GetFile'-TextStream.ReadAll'-TextStream.Close'-File.OpenAsTextStream'-TextStream.AtEndOfStream'-TextStream.ReadLine'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
FunctionGetLyrics(FSO)
DimTextStream
DimS DimFile
'Thereareseveralwaystoopenatextfile,andseveralwaystoreadthe 'dataoutofafile.Here'stwowaystodoeach:
SetTextStream=FSO.OpenTextFile(TestFilePath&"\Beatles\OctopusGarden.txt",OpenFileForReading) S=TextStream.ReadAll&NewLine&NewLine TextStream.Close
SetFile=FSO.GetFile(TestFilePath&"\Beatles\BathroomWindow.txt") SetTextStream=File.OpenAsTextStream(OpenFileForReading) Do WhileNotTextStream.AtEndOfStream S=S&TextStream.ReadLine&NewLine Loop TextStream.Close
GetLyrics=SEndFunction
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''BuildTestDirectory''Purpose:''BuildsadirectoryhierarchytodemonstratetheFileSystemObject.''We'llbuildahierarchyinthisorder:''C:\Test'C:\Test\ReadMe.txt'C:\Test\Beatles'C:\Test\Beatles\OctopusGarden.txt'C:\Test\Beatles\BathroomWindow.txt'''Demonstratesthefollowing''-FileSystemObject.DriveExists'-FileSystemObject.FolderExists'-FileSystemObject.CreateFolder'-FileSystemObject.CreateTextFile'-Folders.Add'-Folder.CreateTextFile'-TextStream.WriteLine'-TextStream.Close
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
FunctionBuildTestDirectory(FSO) DimTestFolder DimSubFolders DimSubFolder DimTextStream
'Bailoutif(a)thedrivedoesnotexist,orif(b)thedirectorybeingbuilt 'alreadyexists.
IfNotFSO.DriveExists(TestDrive)Then BuildTestDirectory=False ExitFunction EndIf
IfFSO.FolderExists(TestFilePath)Then BuildTestDirectory=False ExitFunction EndIf
SetTestFolder=FSO.CreateFolder(TestFilePath)
SetTextStream=FSO.CreateTextFile(TestFilePath&"\ReadMe.txt") TextStream.WriteLine("Mysonglyricscollection") TextStream.Close
SetSubFolders=TestFolder.SubFolders
SetSubFolder=SubFolders.Add("Beatles")
CreateLyricsSubFolder
BuildTestDirectory=True
EndFunction
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Themainroutine''First,itcreatesatestdirectory,alongwithsomesubfoldersandfiles.'Then,itdumpssomeinformationabouttheavailablediskdrivesand'aboutthetestdirectory,andthencleanseverythingupagain.'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
SubMain
DimFSO
'Setupglobaldata. TabStop=Chr(9) NewLine=Chr(10) SetFSO=CreateObject("Scripting.FileSystemObject")
IfNotBuildTestDirectory(FSO)Then Print"Testdirectoryalreadyexistsorcannotbecreated.Cannotcontinue." ExitSub EndIf PrintGenerateDriveInformation(FSO)&NewLine&NewLine
PrintGenerateTestInformation(FSO)&NewLine&NewLine
PrintGetLyrics(FSO)&NewLine&NewLine
DeleteTestDirectory(FSO)EndSub
Microsoft®VisualBasic®ScriptingEdition
VBScriptFeatures LanguageReference
Category Keywords
Arrayhandling
ArrayDim,Private,Public,ReDimIsArrayEraseLBound,UBound
Assignments SetComments Commentsusing'orRem
Constants/Literals
EmptyNothingNullTrue,False
Controlflow
Do...LoopFor...NextForEach...NextIf...Then...ElseSelectCaseWhile...WendWith
Conversions
AbsAsc,AscB,AscWChr,ChrB,ChrWCBool,CByteCCur,CDateCDbl,CIntCLng,CSng,CStrDateSerial,DateValueHex,OctFix,IntSgnTimeSerial,TimeValue
Dates/Times
Date,TimeDateAdd,DateDiff,DatePartDateSerial,DateValueDay,Month,MonthNameWeekday,WeekdayName,YearHour,Minute,SecondNowTimeSerial,TimeValueClassConst
Declarations Dim,Private,Public,ReDimFunction,SubPropertyGet,PropertyLet,PropertySet
ErrorHandling OnErrorErr
Expressions
EvalExecuteRegExpReplaceTest
FormattingStrings
FormatCurrencyFormatDateTimeFormatNumberFormatPercent
Input/OutputInputBoxLoadPictureMsgBox
Literals
EmptyFalseNothingNullTrue
MathAtn,Cos,Sin,TanExp,Log,SqrRandomize,Rnd
MiscellaneousEvalFunctionExecuteStatementRGBFunction
Objects
CreateObjectErrObjectGetObjectRegExp
Operators
Addition(+),Subtraction(-)Exponentiation(^)Modulusarithmetic(Mod)Multiplication(*),Division(/)IntegerDivision(\)Negation(-)Stringconcatenation(&)Equality(=),Inequality(<>)LessThan(<),LessThanorEqualTo(<=)GreaterThan(>)GreaterThanorEqualTo(>=)IsAnd,Or,XorEqv,Imp
Options OptionExplicitCallFunction,Sub
Procedures PropertyGet,PropertyLet,PropertySet
RoundingAbsInt,Fix,RoundSgn
ScriptEngineID
ScriptEngineScriptEngineBuildVersionScriptEngineMajorVersionScriptEngineMinorVersion
Strings
Asc,AscB,AscWChr,ChrB,ChrWFilter,InStr,InStrBInStrRevJoinLen,LenBLCase,UCaseLeft,LeftBMid,MidBRight,RightBReplaceSpaceSplitStrCompStringStrReverseLTrim,RTrim,Trim
Variants
IsArrayIsDateIsEmptyIsNullIsNumericIsObjectTypeNameVarType
Microsoft®VisualBasic®ScriptingEditionVisualBasicforApplicationsFeaturesnotinVBScript
LanguageReference
Category OmittedFeature/Keyword
ArrayHandling OptionBaseDeclaringarrayswithlowerbound<>0
CollectionAdd,Count,Item,RemoveAccesstocollectionsusing!character(e.g.,MyCollection!Foo)
ConditionalCompilation
#Const#If...Then...#Else
ControlFlow
DoEventsGoSub...Return,GoToOnErrorGoToOn...GoSub,On...GoToLinenumbers,Linelabels
Conversion CVar,CVDateStr,Val
DataTypes AllintrinsicdatatypesexceptVariantType...EndType
Date/Time Datestatement,Timestatement
DDE LinkExecute,LinkPoke,LinkRequest,LinkSendDebug.Print
Debugging End,Stop
Declaration
Declare(fordeclaringDLLs)OptionalParamArrayStatic
ErrorHandlingErlErrorResume,ResumeNext
FileInput/Output AlltraditionalBasicfileI/OFinancial AllfinancialfunctionsObjectManipulation TypeOf
Objects ClipboardCollection
Operators Like
Options
DeftypeOptionBaseOptionCompareOptionPrivateModule
SelectCase
ExpressionscontainingIskeywordoranycomparisonoperatorsExpressionscontainingarangeofvaluesusingtheTokeyword.
Strings
Fixed-lengthstringsLSet,RSetMidStatementStrConv
UsingObjects Collectionaccessusing!
Microsoft®VisualBasic®ScriptingEdition
VBScriptFeaturesnotinVisualBasicforApplications
LanguageReference
Category Feature/KeywordDeclarations Class
Miscellaneous EvalExecute
Objects RegExp
ScriptEngineIdentification
ScriptEngineScriptEngineBuildVersionScriptEngineMajorVersionScriptEngineMinorVersion
Microsoft®VisualBasic®ScriptingEdition
MicrosoftScriptingRun-TimeLibraryReferenceFeatures
LanguageReference
Category Feature/Keyword
CollectionsDrivesFilesFolders
DataStorage Dictionary
Dictionary
AddExistsItems,KeysRemove,RemoveAllCountItem,Key
FileSystem
DriveFileFileSystemObjectFolderTextStreamBuildPathCopyFile,CopyFolderCreateFolder,CreateTextFileDeleteFile,DeleteFolderDriveExists,FileExists,FolderExistsGetAbsolutePathName,GetBaseName
FileSystemObject GetDrive,GetDriveNameGetFile,GetExtensionNameGetFileNameGetFolder,GetParentFolderNameGetSpecialFolderGetTempNameMoveFile,MoveFolderOpenTextFileDrives
Drive,Drives
AvailableSpaceCountDriveLetterDriveTypeFileSystemFreeSpaceIsReadyItemRootFolderSerialNumberShareNameTotalSizeVolumeName
File,FilesFolder,Folders
AddAttributesCopy,Delete,MoveCountOpenAsTextStreamDateCreated,DateLastAccessed,DateLastModifiedDriveItemParentFolderName,PathShortName,ShortPathSizeCloseRead,ReadAll,ReadLine
TextStream Skip,SkipLineWrite,WriteBlankLines,WriteLineAtEndOfLine,AtEndOfStreamColumn,Line
Microsoft®VisualBasic®ScriptingEditionAbsFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnstheabsolutevalueofanumber.
Syntax
Abs(number)
Thenumberargumentcanbeanyvalidnumericexpression.IfnumbercontainsNull,Nullisreturned;ifitisanuninitializedvariable,zeroisreturned.
Remarks
Theabsolutevalueofanumberisitsunsignedmagnitude.Forexample,Abs(-1)andAbs(1)bothreturn1.
ThefollowingexampleusestheAbsfunctiontocomputetheabsolutevalueofanumber:
DimMyNumberMyNumber=Abs(50.3)'Returns50.3.MyNumber=Abs(-50.3)'Returns50.3.
Microsoft®VisualBasic®ScriptingEdition+Operator
ScriptingRun-TimeReferenceVersion1
SeeAlso
Description
Sumstwonumbers.
Syntax
result=expression1+expression2
The+operatorsyntaxhastheseparts:
Part Descriptionresult Anynumericvariable.expression1 Anyexpression.expression2 Anyexpression.
Remarks
Althoughyoucanalsousethe+operatortoconcatenatetwocharacterstrings,youshouldusethe&operatorforconcatenationtoeliminateambiguityandprovideself-documentingcode.
Whenyouusethe+operator,youmaynotbeabletodeterminewhetheradditionorstringconcatenationwilloccur.
Theunderlyingsubtypeoftheexpressionsdeterminesthebehaviorofthe+operatorinthefollowingway:
If ThenBothexpressionsarenumeric Add.Bothexpressionsarestrings Concatenate.
Add.
Oneexpressionisnumericandtheotherisastring
IfoneorbothexpressionsareNullexpressions,resultisNull.IfbothexpressionsareEmpty,resultisanIntegersubtype.However,ifonlyoneexpressionisEmpty,theotherexpressionisreturnedunchangedasresult.
Microsoft®VisualBasic®ScriptingEditionAndOperator
LanguageReferenceVersion1
SeeAlso
Description
Performsalogicalconjunctionontwoexpressions.
Syntax
result=expression1Andexpression2
TheAndoperatorsyntaxhastheseparts:
Part Descriptionresult Anynumericvariable.expression1 Anyexpression.expression2 Anyexpression.
Remarks
If,andonlyif,bothexpressionsevaluatetoTrue,resultisTrue.IfeitherexpressionevaluatestoFalse,resultisFalse.Thefollowingtableillustrateshowresultisdetermined:
Ifexpression1is Andexpression2is TheresultisTrue True TrueTrue False FalseTrue Null NullFalse True FalseFalse False FalseFalse Null False
Null True NullNull False FalseNull Null Null
TheAndoperatoralsoperformsabitwisecomparisonofidenticallypositionedbitsintwonumericexpressionsandsetsthecorrespondingbitinresultaccordingtothefollowingtable:
Ifbitinexpression1is Andbitinexpression2is Theresultis0 0 00 1 01 0 01 1 1
Microsoft®VisualBasic®ScriptingEditionArrayFunction
LanguageReferenceVersion2
SeeAlso
Description
ReturnsaVariantcontaininganarray.
Syntax
Array(arglist)
Therequiredarglistargumentisacomma-delimitedlistofvaluesthatareassignedtotheelementsofanarraycontainedwiththeVariant.Ifnoargumentsarespecified,anarrayofzerolengthiscreated.
Remarks
Thenotationusedtorefertoanelementofanarrayconsistsofthevariablenamefollowedbyparenthesescontaininganindexnumberindicatingthedesiredelement.Inthefollowingexample,thefirststatementcreatesavariablenamedA.ThesecondstatementassignsanarraytovariableA.Thelaststatementassignsthevaluecontainedinthesecondarrayelementtoanothervariable.
DimAA=Array(10,20,30)B=A(2)'Bisnow30.
NoteVersionVersionAvariablethatisnotdeclaredasanarraycanstillcontainanarray.AlthoughaVariantvariablecontaininganarrayisconceptuallydifferentfromanarrayvariablecontainingVariantelements,thearrayelementsareaccessedinthesameway.
Microsoft®VisualBasic®ScriptingEditionAscFunction
LanguageReferenceVersion1
SeeAlso
Description
ReturnstheANSIcharactercodecorrespondingtothefirstletterinastring.
Syntax
Asc(string)
Thestringargumentisanyvalidstringexpression.Ifthestringcontainsnocharacters,arun-timeerroroccurs.
Remarks
Inthefollowingexample,AscreturnstheANSIcharactercodeofthefirstletterofeachstring:
DimMyNumberMyNumber=Asc("A")'Returns65.MyNumber=Asc("a")'Returns97.MyNumber=Asc("Apple")'Returns65.
NoteTheAscBfunctionisusedwithbytedatacontainedinastring.Insteadofreturningthecharactercodeforthefirstcharacter,AscBreturnsthefirstbyte.AscWisprovidedfor32-
bitplatformsthatuseUnicodecharacters.ItreturnstheUnicode(wide)charactercode,therebyavoidingtheconversionfromUnicodetoANSI.
Microsoft®VisualBasic®ScriptingEdition=Operator
LanguageReferenceVersion1
SeeAlso
Description
Assignsavaluetoavariableorproperty.
Syntax
variable=value
The=operatorsyntaxhastheseparts:
Part Descriptionvariable Anyvariableoranywritableproperty.value Anynumericorstringliteral,constant,orexpression.
Remarks
Thenameontheleftsideoftheequalsigncanbeasimplescalarvariableoranelementofanarray.Propertiesontheleftsideoftheequalsigncanonlybethosepropertiesthatarewritableatruntime.
Microsoft®VisualBasic®ScriptingEditionAtnFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsthearctangentofanumber.
Syntax
Atn(number)
Thenumberargumentcanbeanyvalidnumericexpression.
Remarks
TheAtnfunctiontakestheratiooftwosidesofarighttriangle(number)andreturnsthecorrespondingangleinradians.Theratioisthelengthofthesideoppositetheangledividedbythelengthofthesideadjacenttotheangle.Therangeoftheresultis-pi/2topi/2radians.
Toconvertdegreestoradians,multiplydegreesbypi/180.Toconvertradianstodegrees,multiplyradiansby180/pi.
ThefollowingexampleusesAtntocalculatethevalueofpi:
Dimpipi=4*Atn(1)'Calculatethevalueofpi.
NoteAtnistheinversetrigonometricfunctionofTan,which
takesanangleasitsargumentandreturnstheratiooftwosidesofarighttriangle.DonotconfuseAtnwiththecotangent,whichisthesimpleinverseofatangent(1/tangent).
Microsoft®VisualBasic®ScriptingEditionCallStatement
LanguageReferenceVersion1
Description
TransferscontroltoaSuborFunctionprocedure.
Syntax
[Call]name[argumentlist]
TheCallstatementsyntaxhastheseparts:
Part Description
Call
Optionalkeyword.Ifspecified,youmustencloseargumentlistinparentheses.Forexample:
CallMyProc(0)
nameRequired.Nameoftheproceduretocall.argumentlistOptional.Comma-delimitedlistofvariables,arrays,orexpressionstopasstotheprocedure.
Remarks
YouarenotrequiredtousetheCallkeywordwhencallingaprocedure.However,ifyouusetheCallkeywordtocallaprocedurethatrequiresarguments,argumentlistmustbeenclosedinparentheses.IfyouomittheCallkeyword,youalsomustomittheparenthesesaroundargumentlist.IfyouuseeitherCallsyntaxtocallanyintrinsicoruser-definedfunction,thefunction'sreturnvalueisdiscarded.
CallMyFunction("HelloWorld")
FunctionMyFunction(text) MsgBoxtextEndFunction
Microsoft®VisualBasic®ScriptingEditionCBoolFunction
LanguageReferenceVersion1
SeeAlso
Description
ReturnsanexpressionthathasbeenconvertedtoaVariantofsubtypeBoolean.
Syntax
CBool(expression)
Theexpressionargumentisanyvalidexpression.
Remarks
Ifexpressioniszero,Falseisreturned;otherwise,Trueisreturned.Ifexpressioncan'tbeinterpretedasanumericvalue,arun-timeerroroccurs.
ThefollowingexampleusestheCBoolfunctiontoconvertanexpressiontoaBoolean.Iftheexpressionevaluatestoanonzerovalue,CBoolreturnsTrue;otherwise,itreturnsFalse.
DimA,B,CheckA=5:B=5'Initializevariables.Check=CBool(A=B)'CheckcontainsTrue.A=0'Definevariable.Check=CBool(A)'CheckcontainsFalse.
Microsoft®VisualBasic®ScriptingEditionCByteFunction
LanguageReferenceVersion1
SeeAlso
Description
ReturnsanexpressionthathasbeenconvertedtoaVariantofsubtypeByte.
Syntax
CByte(expression)
Theexpressionargumentisanyvalidexpression.
Remarks
Ingeneral,youcandocumentyourcodeusingthesubtypeconversionfunctionstoshowthattheresultofsomeoperationshouldbeexpressedasaparticulardatatyperatherthanthedefaultdatatype.Forexample,useCBytetoforcebytearithmeticincaseswherecurrency,single-precision,double-precision,orintegerarithmeticnormallywouldoccur.
UsetheCBytefunctiontoprovideinternationallyawareconversionsfromanyotherdatatypetoaBytesubtype.Forexample,differentdecimalseparatorsareproperlyrecognizeddependingonthelocalesettingofyoursystem,asaredifferentthousandseparators.
IfexpressionliesoutsidetheacceptablerangefortheBytesubtype,anerroroccurs.ThefollowingexampleusestheCBytefunctiontoconvertanexpressiontoabyte:
DimMyDouble,MyByteMyDouble=125.5678'MyDoubleisaDouble.MyByte=CByte(MyDouble)'MyBytecontains126.
Microsoft®VisualBasic®ScriptingEditionCCurFunction
LanguageReferenceVersion1
SeeAlso
Description
ReturnsanexpressionthathasbeenconvertedtoaVariantofsubtypeCurrency.
Syntax
CCur(expression)
Theexpressionargumentisanyvalidexpression.
Remarks
Ingeneral,youcandocumentyourcodeusingthesubtypeconversionfunctionstoshowthattheresultofsomeoperationshouldbeexpressedasaparticulardatatyperatherthanthedefaultdatatype.Forexample,useCCurtoforcecurrencyarithmeticincaseswhereintegerarithmeticnormallywouldoccur.
YoushouldusetheCCurfunctiontoprovideinternationallyawareconversionsfromanyotherdatatypetoaCurrencysubtype.Forexample,differentdecimalseparatorsandthousandsseparatorsareproperlyrecognizeddependingonthelocalesettingofyoursystem.
ThefollowingexampleusestheCCurfunctiontoconvertanexpressiontoaCurrency:
DimMyDouble,MyCurrMyDouble=543.214588'MyDoubleisaDouble.MyCurr=CCur(MyDouble*2)'ConvertresultofMyDouble*2(1086.429176)'toaCurrency(1086.4292).
Microsoft®VisualBasic®ScriptingEditionCDateFunction
LanguageReferenceVersion1
SeeAlso
Description
ReturnsanexpressionthathasbeenconvertedtoaVariantofsubtypeDate.
Syntax
CDate(date)
Thedateargumentisanyvaliddateexpression.
Remarks
UsetheIsDatefunctiontodetermineifdatecanbeconvertedtoadateortime.CDaterecognizesdateliteralsandtimeliteralsaswellassomenumbersthatfallwithintherangeofacceptabledates.Whenconvertinganumbertoadate,thewholenumberportionisconvertedtoadate.Anyfractionalpartofthenumberisconvertedtoatimeofday,startingatmidnight.
CDaterecognizesdateformatsaccordingtothelocalesettingofyoursystem.Thecorrectorderofday,month,andyearmaynotbedeterminedifitisprovidedinaformatotherthanoneoftherecognizeddatesettings.Inaddition,alongdateformatisnotrecognizedifitalsocontainstheday-of-the-weekstring.
ThefollowingexampleusestheCDatefunctiontoconvertastringtoa
date.Ingeneral,hardcodingdatesandtimesasstrings(asshowninthisexample)isnotrecommended.Usedateandtimeliterals(suchas#10/19/1962#,#4:45:23PM#)instead.
MyDate="October19,1962" 'Definedate.MyShortDate=CDate(MyDate) 'ConverttoDatedatatype.MyTime="4:35:47PM" 'Definetime.MyShortTime=CDate(MyTime) 'ConverttoDatedatatype.
Microsoft®VisualBasic®ScriptingEditionCDblFunction
LanguageReferenceVersion1
SeeAlso
Description
ReturnsanexpressionthathasbeenconvertedtoaVariantofsubtypeDouble.
Syntax
CDbl(expression)
Theexpressionargumentisanyvalidexpression.
Remarks
Ingeneral,youcandocumentyourcodeusingthesubtypeconversionfunctionstoshowthattheresultofsomeoperationshouldbeexpressedasaparticulardatatyperatherthanthedefaultdatatype.Forexample,useCDblorCSngtoforcedouble-precisionorsingle-precisionarithmeticincaseswherecurrencyorintegerarithmeticnormallywouldoccur.
UsetheCDblfunctiontoprovideinternationallyawareconversionsfromanyotherdatatypetoaDoublesubtype.Forexample,differentdecimalseparatorsandthousandsseparatorsareproperlyrecognizeddependingonthelocalesettingofyoursystem.
ThisexampleusestheCDblfunctiontoconvertanexpressiontoaDouble.
DimMyCurr,MyDouble
MyCurr=CCur(234.456784)'MyCurrisaCurrency(234.4567).MyDouble=CDbl(MyCurr*8.2*0.01)'ConvertresulttoaDouble(19.2254576).
Microsoft®VisualBasic®ScriptingEditionChrFunction
LanguageReferenceVersion1
SeeAlso
Description
ReturnsthecharacterassociatedwiththespecifiedANSIcharactercode.
Syntax
Chr(charcode)
Thecharcodeargumentisanumberthatidentifiesacharacter.
Remarks
Numbersfrom0to31arethesameasstandard,nonprintableASCIIcodes.Forexample,Chr(10)returnsalinefeedcharacter.
ThefollowingexampleusestheChrfunctiontoreturnthecharacterassociatedwiththespecifiedcharactercode:
DimMyCharMyChar=Chr(65)'ReturnsA.MyChar=Chr(97)'Returnsa.MyChar=Chr(62)'Returns>.MyChar=Chr(37)'Returns%.
NoteTheChrBfunctionisusedwithbytedatacontainedinastring.Insteadofreturningacharacter,whichmaybeoneortwobytes,ChrBalwaysreturnsasinglebyte.ChrWisprovidedfor32-bitplatformsthatuseUnicodecharacters.ItsargumentisaUnicode(wide)charactercode,therebyavoidingtheconversionfromANSItoUnicode.
Microsoft®VisualBasic®ScriptingEditionCIntFunction
LanguageReferenceVersion1
SeeAlso
Description
ReturnsanexpressionthathasbeenconvertedtoaVariantofsubtypeInteger.
Syntax
CInt(expression)
Theexpressionargumentisanyvalidexpression.
Remarks
Ingeneral,youcandocumentyourcodeusingthesubtypeconversionfunctionstoshowthattheresultofsomeoperationshouldbeexpressedasaparticulardatatyperatherthanthedefaultdatatype.Forexample,useCIntorCLngtoforceintegerarithmeticincaseswherecurrency,single-precision,ordouble-precisionarithmeticnormallywouldoccur.
UsetheCIntfunctiontoprovideinternationallyawareconversionsfromanyotherdatatypetoanIntegersubtype.Forexample,differentdecimalseparatorsareproperlyrecognizeddependingonthelocalesettingofyoursystem,asaredifferentthousandseparators.
IfexpressionliesoutsidetheacceptablerangefortheIntegersubtype,anerroroccurs.
ThefollowingexampleusestheCIntfunctiontoconvertavaluetoan
Integer:
DimMyDouble,MyIntMyDouble=2345.5678'MyDoubleisaDouble.MyInt=CInt(MyDouble)'MyIntcontains2346.
NoteCIntdiffersfromtheFixandIntfunctions,whichtruncate,ratherthanround,thefractionalpartofanumber.Whenthefractionalpartisexactly0.5,theCIntfunctionalwaysroundsittothenearestevennumber.Forexample,0.5roundsto0,and1.5roundsto2.
Microsoft®VisualBasic®ScriptingEditionClassObject
LanguageReferenceVersion5
SeeAlsoEvents
Description
TheobjectcreatedusingtheClassstatement.Providesaccesstotheeventsoftheclass.
Remarks
YoucannotexplicitlydeclareavariabletobeoftypeClass.IntheVBScriptcontext,theterm"classobject"referstoanyobjectdefinedusingtheVBScriptClassstatement.
OnceyouhavecreatedaclassdefinitionusingtheClassstatement,youcancreateaninstanceoftheclassusingthefollowingform:
DimXSetX=Newclassname
BecauseVBScriptisalate-boundlanguage,youcannotdoanyofthefollowing:
DimXasNewclassname
or
DimX
X=Newclassname
or
SetX=NewScripting.FileSystemObject
Microsoft®VisualBasic®ScriptingEditionClassStatement
LanguageReferenceVersion5
SeeAlso
Description
Declaresthenameofaclass,aswellasadefinitionofthevariables,properties,andmethodsthatcomprisetheclass.
Syntax
ClassnamestatementsEndClass
TheClassstatementsyntaxhastheseparts:
Part Descriptionname Required.NameoftheClass;followsstandardvariablenamingconventions.
statements Required.Oneormorestatementsthatdefinethevariables,properties,andmethodsoftheClass.
Remarks
WithinaClassblock,membersaredeclaredaseitherPrivateorPublicusingtheappropriatedeclarationstatements.AnythingdeclaredasPrivateisvisibleonlywithintheClassblock.AnythingdeclaredasPublicisvisiblewithintheClassblock,aswellasbycodeoutsidetheClassblock.AnythingnotexplicitlydeclaredaseitherPrivateorPublicisPublicbydefault.
Procedures(eitherSuborFunction)declaredPublicwithintheclassblockbecomemethodsoftheclass.Publicvariablesserveaspropertiesoftheclass,asdopropertiesexplicitlydeclaredusingPropertyGet,PropertyLet,andPropertySet.DefaultpropertiesandmethodsfortheclassarespecifiedintheirdeclarationsusingtheDefaultkeyword.Seetheindividualdeclarationstatementtopicsforinformationonhowthiskeywordisused.
Microsoft®VisualBasic®ScriptingEditionClearMethod
LanguageReferenceVersion1
SeeAlsoAppliesto
Description
ClearsallpropertysettingsoftheErrobject.
Syntax
object.Clear
TheobjectisalwaystheErrobject.
Remarks
UseCleartoexplicitlycleartheErrobjectafteranerrorhasbeenhandled.Thisisnecessary,forexample,whenyouusedeferrederrorhandlingwithOnErrorResumeNext.VBScriptcallstheClearmethodautomaticallywheneveranyofthefollowingstatementsisexecuted:
OnErrorResumeNext
ExitSub
ExitFunction
ThefollowingexampleillustratesuseoftheClearmethod:
OnErrorResumeNextErr.Raise6'Raiseanoverflowerror.MsgBox("Error#"&CStr(Err.Number)&""&Err.Description)Err.Clear'Cleartheerror.
Microsoft®VisualBasic®ScriptingEditionCLngFunction
LanguageReferenceVersion1
SeeAlso
Description
ReturnsanexpressionthathasbeenconvertedtoaVariantofsubtypeLong.
Syntax
CLng(expression)
Theexpressionargumentisanyvalidexpression.
Remarks
Ingeneral,youcandocumentyourcodeusingthesubtypeconversionfunctionstoshowthattheresultofsomeoperationshouldbeexpressedasaparticulardatatyperatherthanthedefaultdatatype.Forexample,useCIntorCLngtoforceintegerarithmeticincaseswherecurrency,single-precision,ordouble-precisionarithmeticnormallywouldoccur.
UsetheCLngfunctiontoprovideinternationallyawareconversionsfromanyotherdatatypetoaLongsubtype.Forexample,differentdecimalseparatorsareproperlyrecognizeddependingonthelocalesettingofyoursystem,asaredifferentthousandseparators.
IfexpressionliesoutsidetheacceptablerangefortheLongsubtype,anerroroccurs.
ThefollowingexampleusestheCLngfunctiontoconvertavaluetoa
Long:
DimMyVal1,MyVal2,MyLong1,MyLong2MyVal1=25427.45:MyVal2=25427.55 'MyVal1,MyVal2areDoubles.MyLong1=CLng(MyVal1) 'MyLong1contains25427.MyLong2=CLng(MyVal2) 'MyLong2contains25428.
NoteCLngdiffersfromtheFixandIntfunctions,whichtruncate,ratherthanround,thefractionalpartofanumber.Whenthefractionalpartisexactly0.5,theCLngfunctionalwaysroundsittothenearestevennumber.Forexample,0.5roundsto0,and1.5roundsto2.
Microsoft®VisualBasic®ScriptingEdition
ComparisonConstants
LanguageReferenceVersion2
SeeAlso
SincetheseconstantsarebuiltintoVBScript,youdon'thavetodefinethembeforeusingthem.Usethemanywhereinyourcodetorepresentthevaluesshownforeach.
Constant Value DescriptionvbBinaryCompare 0 Performabinarycomparison.vbTextCompare 1 Performatextualcomparison.
Microsoft®VisualBasic®ScriptingEdition&Operator
LanguageReferenceVersion1
SeeAlso
Description
Forcesstringconcatenationoftwoexpressions.
Syntax
result=expression1&expression2
The&operatorsyntaxhastheseparts:
Part Descriptionresult Anyvariable.expression1 Anyexpression.expression2 Anyexpression.
Remarks
Wheneveranexpressionisnotastring,itisconvertedtoaStringsubtype.IfbothexpressionsareNull,resultisalsoNull.However,ifonlyoneexpressionisNull,thatexpressionistreatedasazero-lengthstring("")whenconcatenatedwiththeotherexpression.AnyexpressionthatisEmptyisalsotreatedasazero-lengthstring.
Microsoft®VisualBasic®ScriptingEditionConstStatement
LanguageReferenceVersion2
SeeAlso
Description
Declaresconstantsforuseinplaceofliteralvalues.
Syntax
[Public|Private]Constconstname=expression
TheConststatementsyntaxhastheseparts:
Part Description
PublicOptional.Keywordusedatscriptleveltodeclareconstantsthatareavailabletoallproceduresinallscripts.Notallowedinprocedures.
Private
Optional.Keywordusedatscriptleveltodeclareconstantsthatareavailableonlywithinthescriptwherethedeclarationismade.Notallowedinprocedures.
constname Required.Nameoftheconstant;followsstandardvariablenamingconventions.
expressionRequired.Literalorotherconstant,oranycombinationthatincludesallarithmeticorlogicaloperatorsexceptIs.
Remarks
Constantsarepublicbydefault.Withinprocedures,constantsarealwaysprivate;theirvisibilitycan'tbechanged.Withinascript,thedefaultvisibilityofascript-levelconstantcanbechangedusingthePrivate
keyword.
Tocombineseveralconstantdeclarationsonthesameline,separateeachconstantassignmentwithacomma.Whenconstantdeclarationsarecombinedinthisway,thePublicorPrivatekeyword,ifused,appliestoallofthem.
Youcan'tusevariables,user-definedfunctions,orintrinsicVBScriptfunctions(suchasChr)inconstantdeclarations.Bydefinition,theycan'tbeconstants.Youalsocan'tcreateaconstantfromanyexpressionthatinvolvesanoperator,thatis,onlysimpleconstantsareallowed.ConstantsdeclaredinaSuborFunctionprocedurearelocaltothatprocedure.Aconstantdeclaredoutsideaprocedureisdefinedthroughoutthescriptinwhichitisdeclared.Youcanuseconstantsanywhereyoucanuseanexpression.ThefollowingcodeillustratestheuseoftheConststatement:
ConstMyVar=459 'ConstantsarePublicbydefault.PrivateConstMyString="HELP" 'DeclarePrivateconstant.ConstMyStr="Hello",MyNumber=3.4567 'Declaremultipleconstantsonsameline.
NoteConstantscanmakeyourscriptsself-documentingandeasytomodify.Unlikevariables,constantscan'tbeinadvertentlychangedwhileyourscriptisrunning.
Microsoft®VisualBasic®ScriptingEditionCosFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsthecosineofanangle.
Syntax
Cos(number)
Thenumberargumentcanbeanyvalidnumericexpressionthatexpressesanangleinradians.
Remarks
TheCosfunctiontakesanangleandreturnstheratiooftwosidesofarighttriangle.Theratioisthelengthofthesideadjacenttotheangledividedbythelengthofthehypotenuse.Theresultliesintherange-1to1.
Toconvertdegreestoradians,multiplydegreesbypi/180.Toconvertradianstodegrees,multiplyradiansby180/pi.
ThefollowingexampleusestheCosfunctiontoreturnthecosineofanangle:
DimMyAngle,MySecantMyAngle=1.3'Defineangleinradians.MySecant=1/Cos(MyAngle)'Calculatesecant.
Microsoft®VisualBasic®ScriptingEdition
CreateObjectFunction
LanguageReferenceVersion2
SeeAlso
Description
CreatesandreturnsareferencetoanAutomationobject.
Syntax
CreateObject(servername.typename[,location])
TheCreateObjectfunctionsyntaxhastheseparts:
Part Description
servername Required.Thenameoftheapplicationprovidingtheobject.typename Required.Thetypeorclassoftheobjecttocreate.
locationOptional.Thenameofthenetworkserverwheretheobjectistobecreated.Thisfeatureisavailableinversion5.1orlater.
Remarks
Automationserversprovideatleastonetypeofobject.Forexample,aword-processingapplicationmayprovideanapplicationobject,adocumentobject,andatoolbarobject.
TocreateanAutomationobject,assigntheobjectreturnedbyCreateObjecttoanobjectvariable:
DimExcelSheetSetExcelSheet=CreateObject("Excel.Sheet")
Thiscodestartstheapplicationthatcreatestheobject(inthiscase,aMicrosoftExcelspreadsheet).Onceanobjectiscreated,refertoitincodeusingtheobjectvariableyoudefined.Asshowninthefollowingexample,youcanaccesspropertiesandmethodsofthenewobjectusingtheobjectvariable,ExcelSheet,andotherExcelobjects,includingtheApplicationobjectandtheActiveSheet.Cellscollection:
'MakeExcelvisiblethroughtheApplicationobject.ExcelSheet.Application.Visible=True'Placesometextinthefirstcellofthesheet.ExcelSheet.ActiveSheet.Cells(1,1).Value="ThisiscolumnA,row1"'Savethesheet.ExcelSheet.SaveAs"C:\DOCS\TEST.XLS"'CloseExcelwiththeQuitmethodontheApplicationobject.ExcelSheet.Application.Quit'Releasetheobjectvariable.SetExcelSheet=Nothing
CreatinganobjectonaremoteservercanonlybeaccomplishedwhenInternetsecurityisturnedoff.YoucancreateanobjectonaremotenetworkedcomputerbypassingthenameofthecomputertotheservernameargumentofCreateObject.Thatnameisthesameasthemachinenameportionofasharename.Foranetworksharenamed"\\myserver\public",theservernameis"myserver".Inaddition,youcanspecifyservernameusingDNSformatoranIPaddress.
ThefollowingcodereturnstheversionnumberofaninstanceofExcelrunningonaremotenetworkcomputernamed"myserver":
FunctionGetVersionDimXLAppSetXLApp=CreateObject("Excel.Application","MyServer")
GetVersion=XLApp.VersionEndFunction
Anerroroccursifthespecifiedremoteserverdoesnotexistorcannotbefound.
Microsoft®VisualBasic®ScriptingEditionCSngFunction
LanguageReferenceVersion1
SeeAlso
Description
ReturnsanexpressionthathasbeenconvertedtoaVariantofsubtypeSingle.
Syntax
CSng(expression)
Theexpressionargumentisanyvalidexpression.
Remarks
Ingeneral,youcandocumentyourcodeusingthedatatypeconversionfunctionstoshowthattheresultofsomeoperationshouldbeexpressedasaparticulardatatyperatherthanthedefaultdatatype.Forexample,useCDblorCSngtoforcedouble-precisionorsingle-precisionarithmeticincaseswherecurrencyorintegerarithmeticnormallywouldoccur.
UsetheCSngfunctiontoprovideinternationallyawareconversionsfromanyotherdatatypetoaSinglesubtype.Forexample,differentdecimalseparatorsareproperlyrecognizeddependingonthelocalesettingofyoursystem,asaredifferentthousandseparators.
IfexpressionliesoutsidetheacceptablerangefortheSinglesubtype,anerroroccurs.
ThefollowingexampleusestheCSngfunctiontoconvertavaluetoa
Single:
DimMyDouble1,MyDouble2,MySingle1,MySingle2 'MyDouble1,MyDouble2areDoubles.MyDouble1=75.3421115:MyDouble2=75.3421555MySingle1=CSng(MyDouble1) 'MySingle1contains75.34211.MySingle2=CSng(MyDouble2) 'MySingle2contains75.34216.
Microsoft®VisualBasic®ScriptingEditionCStrFunction
LanguageReferenceVersion1
SeeAlso
Description
ReturnsanexpressionthathasbeenconvertedtoaVariantofsubtypeString.
Syntax
CStr(expression)
Theexpressionargumentisanyvalidexpression.
Remarks
Ingeneral,youcandocumentyourcodeusingthedatatypeconversionfunctionstoshowthattheresultofsomeoperationshouldbeexpressedasaparticulardatatyperatherthanthedefaultdatatype.Forexample,useCStrtoforcetheresulttobeexpressedasaString.
YoushouldusetheCStrfunctioninsteadofStrtoprovideinternationallyawareconversionsfromanyotherdatatypetoaStringsubtype.Forexample,differentdecimalseparatorsareproperlyrecognizeddependingonthelocalesettingofyoursystem.
Thedatainexpressiondetermineswhatisreturnedaccordingtothefollowingtable:
If
expressionis
CStrreturns
Boolean AStringcontainingTrueorFalse.
Date AStringcontainingadateintheshort-dateformatofyoursystem.
Null Arun-timeerror.Empty Azero-lengthString("").
Error AStringcontainingthewordErrorfollowedbytheerrornumber.
Othernumeric AStringcontainingthenumber.
ThefollowingexampleusestheCStrfunctiontoconvertanumericvaluetoaString:
DimMyDouble,MyStringMyDouble=437.324'MyDoubleisaDouble.MyString=CStr(MyDouble)'MyStringcontains"437.324".
Microsoft®VisualBasic®ScriptingEditionDateandTimeConstants
LanguageReferenceVersion2
SeeAlso
SincetheseconstantsarebuiltintoVBScript,youdon'thavetodefinethembeforeusingthem.Usethemanywhereinyourcodetorepresentthevaluesshownforeach.
Constant Value DescriptionvbSunday 1 SundayvbMonday 2 MondayvbTuesday 3 TuesdayvbWednesday 4 WednesdayvbThursday 5 ThursdayvbFriday 6 FridayvbSaturday 7 Saturday
vbUseSystem 0Usethedateformatcontainedintheregionalsettingsforyourcomputer.
vbUseSystemDayOfWeek 0
Usethedayoftheweekspecifiedinyoursystemsettingsforthefirstdayoftheweek.
vbFirstJan1 1 UsetheweekinwhichJanuary1occurs(default).
vbFirstFourDays 2Usethefirstweekthathasatleastfourdaysinthenewyear.
vbFirstFullWeek 3 Usethefirstfullweekoftheyear.
Microsoft®VisualBasic®ScriptingEditionDateFormatConstants
LanguageReferenceVersion2
SeeAlso
SincetheseconstantsarebuiltintoVBScript,youdon'thavetodefinethembeforeusingthem.Usethemanywhereinyourcodetorepresentthevaluesshownforeach.
Constant Value Description
vbGeneralDate 0
Displayadateand/ortime.Forrealnumbers,displayadateandtime.Ifthereisnofractionalpart,displayonlyadate.Ifthereisnointegerpart,displaytimeonly.Dateandtimedisplayisdeterminedbyyoursystemsettings.
vbLongDate 1Displayadateusingthelongdateformatspecifiedinyourcomputer'sregionalsettings.
vbShortDate 2Displayadateusingtheshortdateformatspecifiedinyourcomputer'sregionalsettings.
vbLongTime 3Displayatimeusingthelongtimeformatspecifiedinyourcomputer'sregionalsettings.
vbShortTime 4Displayatimeusingtheshorttimeformatspecifiedinyourcomputer'sregionalsettings.
Microsoft®VisualBasic®ScriptingEditionDateFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsthecurrentsystemdate.
Syntax
Date
Remarks
ThefollowingexampleusestheDatefunctiontoreturnthecurrentsystemdate:
DimMyDateMyDate=Date'MyDatecontainsthecurrentsystemdate.
Microsoft®VisualBasic®ScriptingEdition
DateAddFunctionLanguageReference
Version2
SeeAlso
Description
Returnsadatetowhichaspecifiedtimeintervalhasbeenadded.
Syntax
DateAdd(interval,number,date)
TheDateAddfunctionsyntaxhastheseparts:
Part Description
interval Required.Stringexpressionthatistheintervalyouwanttoadd.SeeSettingssectionforvalues.
number
Required.Numericexpressionthatisthenumberofintervalyouwanttoadd.Thenumericexpressioncaneitherbepositive,fordatesinthefuture,ornegative,fordatesinthepast.
date Required.Variantorliteralrepresentingthedatetowhichintervalisadded.
Settings
Theintervalargumentcanhavethefollowingvalues:
Setting Descriptionyyyy Yearq Quarterm Monthy Dayofyeard Day
w Weekdayww Weekofyearh Hourn Minutes Second
Remarks
YoucanusetheDateAddfunctiontoaddorsubtractaspecifiedtimeintervalfromadate.Forexample,youcanuseDateAddtocalculateadate30daysfromtodayoratime45minutesfromnow.Toadddaystodate,youcanuseDayofYear("y"),Day("d"),orWeekday("w").
TheDateAddfunctionwon'treturnaninvaliddate.ThefollowingexampleaddsonemonthtoJanuary31:
NewDate=DateAdd("m",1,"31-Jan-95")Inthiscase,DateAddreturns28-Feb-95,not31-Feb-95.Ifdateis31-Jan-96,itreturns29-Feb-96because1996isaleapyear.
Ifthecalculateddatewouldprecedetheyear100,anerroroccurs.
Ifnumberisn'taLongvalue,itisroundedtothenearestwholenumberbeforebeingevaluated.
Microsoft®VisualBasic®ScriptingEdition
DateDiffFunctionLanguageReference
Version2
SeeAlso
Description
Returnsthenumberofintervalsbetweentwodates.
Syntax
DateDiff(interval,date1,date2[,firstdayofweek[,firstweekofyear]])
TheDateDifffunctionsyntaxhastheseparts:
Part Description
interval
Required.Stringexpressionthatistheintervalyouwanttousetocalculatethedifferencesbetweendate1anddate2.SeeSettingssectionforvalues.
date1,date2 Required.Dateexpressions.Twodatesyouwanttouseinthecalculation.
firstdayofweekOptional.Constantthatspecifiesthedayoftheweek.Ifnotspecified,Sundayisassumed.SeeSettingssectionforvalues.
firstweekofyear
Optional.Constantthatspecifiesthefirstweekoftheyear.Ifnotspecified,thefirstweekisassumedtobetheweekinwhichJanuary1occurs.SeeSettingssectionforvalues.
Settings
Theintervalargumentcanhavethefollowingvalues:
Setting Descriptionyyyy Year
q Quarterm Monthy Dayofyeard Dayw Weekdayww Weekofyearh Hourn Minutes Second
Thefirstdayofweekargumentcanhavethefollowingvalues:
Constant Value Description
vbUseSystem 0 UseNationalLanguageSupport(NLS)APIsetting.
vbSunday 1 Sunday(default)vbMonday 2 MondayvbTuesday 3 TuesdayvbWednesday 4 WednesdayvbThursday 5 ThursdayvbFriday 6 FridayvbSaturday 7 Saturday
Thefirstweekofyearargumentcanhavethefollowingvalues:
Constant Value Description
vbUseSystem 0 UseNationalLanguageSupport(NLS)APIsetting.
vbFirstJan1 1 StartwiththeweekinwhichJanuary1occurs(default).
vbFirstFourDays 2 Startwiththeweekthathasatleastfourdaysinthenewyear.Startwiththefirstfullweekofthenew
vbFirstFullWeek 3 year.
Remarks
YoucanusetheDateDifffunctiontodeterminehowmanyspecifiedtimeintervalsexistbetweentwodates.Forexample,youmightuseDateDifftocalculatethenumberofdaysbetweentwodates,orthenumberofweeksbetweentodayandtheendoftheyear.
Tocalculatethenumberofdaysbetweendate1anddate2,youcanuseeitherDayofyear("y")orDay("d").WhenintervalisWeekday("w"),DateDiffreturnsthenumberofweeksbetweenthetwodates.Ifdate1fallsonaMonday,DateDiffcountsthenumberofMondaysuntildate2.Itcountsdate2butnotdate1.IfintervalisWeek("ww"),however,theDateDifffunctionreturnsthenumberofcalendarweeksbetweenthetwodates.ItcountsthenumberofSundaysbetweendate1anddate2.DateDiffcountsdate2ifitfallsonaSunday;butitdoesn'tcountdate1,evenifitdoesfallonaSunday.
Ifdate1referstoalaterpointintimethandate2,theDateDifffunctionreturnsanegativenumber.
Thefirstdayofweekargumentaffectscalculationsthatusethe"w"and"ww"intervalsymbols.
Ifdate1ordate2isadateliteral,thespecifiedyearbecomesapermanentpartofthatdate.However,ifdate1ordate2isenclosedinquotationmarks("")andyouomittheyear,thecurrentyearisinsertedinyourcodeeachtimethedate1ordate2expressionisevaluated.Thismakesitpossibletowritecodethatcanbeusedindifferentyears.
WhencomparingDecember31toJanuary1oftheimmediatelysucceedingyear,DateDiffforYear("yyyy")returns1eventhoughonlyadayhaselapsed.
ThefollowingexampleusestheDateDifffunctiontodisplaythenumberofdaysbetweenagivendateandtoday:
FunctionDiffADate(theDate)DiffADate="Daysfromtoday:"&DateDiff("d",Now,theDate)EndFunction
Microsoft®VisualBasic®ScriptingEdition
DatePartFunctionLanguageReference
Version2
SeeAlso
Description
Returnsthespecifiedpartofagivendate.
Syntax
DatePart(interval,date[,firstdayofweek[,firstweekofyear]])
TheDatePartfunctionsyntaxhastheseparts:
Part Description
intervalRequired.Stringexpressionthatistheintervaloftimeyouwanttoreturn.SeeSettingssectionforvalues.
date Required.Dateexpressionyouwanttoevaluate.
firstdayofweekOptional.Constantthatspecifiesthedayoftheweek.Ifnotspecified,Sundayisassumed.SeeSettingssectionforvalues.
firstweekofyear
Optional.Constantthatspecifiesthefirstweekoftheyear.Ifnotspecified,thefirstweekisassumedtobetheweekinwhichJanuary1occurs.SeeSettingssectionforvalues.
Settings
Theintervalargumentcanhavethefollowingvalues:
Setting Descriptionyyyy Yearq Quarter
m Monthy Dayofyeard Dayw Weekdayww Weekofyearh Hourn Minutes Second
Thefirstdayofweekargumentcanhavethefollowingvalues:
Constant Value Description
vbUseSystem 0 UseNationalLanguageSupport(NLS)APIsetting.
vbSunday 1 Sunday(default)vbMonday 2 MondayvbTuesday 3 TuesdayvbWednesday 4 WednesdayvbThursday 5 ThursdayvbFriday 6 FridayvbSaturday 7 Saturday
Thefirstweekofyearargumentcanhavethefollowingvalues:
Constant Value Description
vbUseSystem 0 UseNationalLanguageSupport(NLS)APIsetting.
vbFirstJan1 1 StartwiththeweekinwhichJanuary1occurs(default).
vbFirstFourDays 2 Startwiththeweekthathasatleastfourdaysinthenewyear.
vbFirstFullWeek 3 Startwiththefirstfullweekofthenewyear.
Remarks
YoucanusetheDatePartfunctiontoevaluateadateandreturnaspecificintervaloftime.Forexample,youmightuseDateParttocalculatethedayoftheweekorthecurrenthour.
Thefirstdayofweekargumentaffectscalculationsthatusethe"w"and"ww"intervalsymbols.
Ifdateisadateliteral,thespecifiedyearbecomesapermanentpartofthatdate.However,ifdateisenclosedinquotationmarks(""),andyouomittheyear,thecurrentyearisinsertedinyourcodeeachtimethedateexpressionisevaluated.Thismakesitpossibletowritecodethatcanbeusedindifferentyears.
Thisexampletakesadateand,usingtheDatePartfunction,displaysthequarteroftheyearinwhichitoccurs.
FunctionGetQuarter(TheDate)GetQuarter=DatePart("q",TheDate)EndFunction
Microsoft®VisualBasic®ScriptingEdition
DateSerialFunction
LanguageReferenceVersion1
SeeAlso
Description
ReturnsaVariantofsubtypeDateforaspecifiedyear,month,andday.
Syntax
DateSerial(year,month,day)
TheDateSerialfunctionsyntaxhasthesearguments:
Part Description
year Numberbetween100and9999,inclusive,oranumericexpression.
month Anynumericexpression.day Anynumericexpression.
Remarks
Tospecifyadate,suchasDecember31,1991,therangeofnumbersforeachDateSerialargumentshouldbeintheacceptedrangefortheunit;thatis,1–31fordaysand1–12formonths.However,youcanalsospecifyrelativedatesforeachargumentusinganynumericexpressionthatrepresentssomenumberofdays,months,oryearsbeforeorafteracertaindate.
Thefollowingexampleusesnumericexpressionsinsteadofabsolutedate
numbers.HeretheDateSerialfunctionreturnsadatethatisthedaybeforethefirstday(1–1)oftwomonthsbeforeAugust(8–2)of10yearsbefore1990(1990–10);inotherwords,May31,1980.
DimMyDate1,MyDate2MyDate1=DateSerial(1970,1,1) 'ReturnsJanuary1,1970.MyDate2=DateSerial(1990-10,8-2,1-1) 'ReturnsMay31,1980.
Fortheyearargument,valuesbetween0and99,inclusive,areinterpretedastheyears1900–1999.Forallotheryeararguments,useacompletefour-digityear(forexample,1800).
Whenanyargumentexceedstheacceptedrangeforthatargument,itincrementstothenextlargerunitasappropriate.Forexample,ifyouspecify35days,itisevaluatedasonemonthandsomenumberofdays,dependingonwhereintheyearitisapplied.However,ifanysingleargumentisoutsidetherange-32,768to32,767,orifthedatespecifiedbythethreearguments,eitherdirectlyorbyexpression,fallsoutsidetheacceptablerangeofdates,anerroroccurs.
Microsoft®VisualBasic®ScriptingEdition
DateValueFunction
LanguageReferenceVersion1
SeeAlso
Description
ReturnsaVariantofsubtypeDate.
Syntax
DateValue(date)
ThedateargumentisnormallyastringexpressionrepresentingadatefromJanuary1,100throughDecember31,9999.However,datecanalsobeanyexpressionthatcanrepresentadate,atime,orbothadateandtime,inthatrange.
Remarks
Ifthedateargumentincludestimeinformation,DateValuedoesn'treturnit.However,ifdateincludesinvalidtimeinformation(suchas"89:98"),anerroroccurs.
Ifdateisastringthatincludesonlynumbersseparatedbyvaliddateseparators,DateValuerecognizestheorderformonth,day,andyearaccordingtotheshortdateformatyouspecifiedforyoursystem.DateValuealsorecognizesunambiguousdatesthatcontainmonthnames,eitherinlongorabbreviatedform.Forexample,inadditiontorecognizing12/30/1991and12/30/91,DateValuealsorecognizesDecember30,1991andDec30,1991.
Iftheyearpartofdateisomitted,DateValueusesthecurrentyearfromyourcomputer'ssystemdate.
ThefollowingexampleusestheDateValuefunctiontoconvertastringtoadate.YoucanalsousedateliteralstodirectlyassignadatetoaVariantvariable,forexample,MyDate=#9/11/63#.
DimMyDateMyDate=DateValue("September11,1963")'Returnadate.
Microsoft®VisualBasic®ScriptingEditionDayFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsawholenumberbetween1and31,inclusive,representingthedayofthemonth.
Syntax
Day(date)
Thedateargumentisanyexpressionthatcanrepresentadate.IfdatecontainsNull,Nullisreturned.
ThefollowingexampleusestheDayfunctiontoobtainthedayofthemonthfromaspecifieddate:
DimMyDayMyDay=Day("October19,1962")'MyDaycontains19.
Microsoft®VisualBasic®ScriptingEdition
DescriptionProperty
LanguageReferenceVersion1
SeeAlsoAppliesto
Description
Returnsorsetsadescriptivestringassociatedwithanerror.
Syntax
object.Description[=stringexpression]
TheDescriptionpropertysyntaxhastheseparts:
Part Descriptionobject AlwaystheErrobject.
stringexpression Astringexpressioncontainingadescriptionoftheerror.
Remarks
TheDescriptionpropertyconsistsofashortdescriptionoftheerror.Usethispropertytoalerttheusertoanerrorthatyoucan'tordon'twanttohandle.Whengeneratingauser-definederror,assignashortdescriptionofyourerrortothisproperty.IfDescriptionisn'tfilledin,andthevalueofNumbercorrespondstoaVBScriptrun-timeerror,thedescriptivestringassociatedwiththeerrorisreturned.
OnErrorResumeNextErr.Raise6'Raiseanoverflowerror.MsgBox("Error#"&CStr(Err.Number)&""&Err.Description)Err.Clear'Cleartheerror.
Microsoft®VisualBasic®ScriptingEditionDimStatement
LanguageReferenceVersion1
SeeAlso
Description
Declaresvariablesandallocatesstoragespace.
Syntax
Dimvarname[([subscripts])][,varname[([subscripts])]]...
TheDimstatementsyntaxhastheseparts:
Part Descriptionvarname Nameofthevariable;followsstandardvariablenamingconventions.
subscripts
Dimensionsofanarrayvariable;upto60multipledimensionsmaybedeclared.Thesubscriptsargumentusesthefollowingsyntax:
upperbound[,upperbound]...
Thelowerboundofanarrayisalwayszero.
Remarks
VariablesdeclaredwithDimatthescriptlevelareavailabletoallprocedureswithinthescript.Attheprocedurelevel,variablesareavailableonlywithintheprocedure.
YoucanalsousetheDimstatementwithemptyparenthesesto
declareadynamicarray.Afterdeclaringadynamicarray,usetheReDimstatementwithinaproceduretodefinethenumberofdimensionsandelementsinthearray.IfyoutrytoredeclareadimensionforanarrayvariablewhosesizewasexplicitlyspecifiedinaDimstatement,anerroroccurs.
TipWhenyouusetheDimstatementinaprocedure,yougenerallyputtheDimstatementatthebeginningoftheprocedure.
ThefollowingexamplesillustratetheuseoftheDimstatement:
DimNames(9)'Declareanarraywith10elements.DimNames()'Declareadynamicarray.DimMyVar,MyNum'Declaretwovariables.
Microsoft®VisualBasic®ScriptingEdition/Operator
LanguageReferenceVersion1
SeeAlso
Description
Dividestwonumbersandreturnsafloating-pointresult.
Syntax
result=number1/number2
The/operatorsyntaxhastheseparts:
Part Descriptionresult Anynumericvariable.number1 Anynumericexpression.number2 Anynumericexpression.
Remarks
IfoneorbothexpressionsareNullexpressions,resultisNull.AnyexpressionthatisEmptyistreatedas0.
Microsoft®VisualBasic®ScriptingEdition
Do...LoopStatement
LanguageReferenceVersion1
SeeAlso
Description
RepeatsablockofstatementswhileaconditionisTrueoruntilaconditionbecomesTrue.
Syntax
Do[{While|Until}condition][statements][ExitDo][statements]Loop
Or,youcanusethissyntax:
Do[statements][ExitDo][statements]Loop[{While|Until}condition]
TheDo...Loopstatementsyntaxhastheseparts:
Part Description
condition NumericorstringexpressionthatisTrueorFalse.IfconditionisNull,conditionistreatedasFalse.
statements OneormorestatementsthatarerepeatedwhileoruntilconditionisTrue.
Remarks
TheExitDocanonlybeusedwithinaDo...Loopcontrolstructureto
provideanalternatewaytoexitaDo...Loop.AnynumberofExitDostatementsmaybeplacedanywhereintheDo...Loop.Oftenusedwiththeevaluationofsomecondition(forexample,If...Then),ExitDotransferscontroltothestatementimmediatelyfollowingtheLoop.
WhenusedwithinnestedDo...Loopstatements,ExitDotransferscontroltotheloopthatisnestedonelevelabovetheloopwhereitoccurs.
ThefollowingexamplesillustrateuseoftheDo...Loopstatement:
DoUntilDefResp=vbNoMyNum=Int(6*Rnd+1)'Generatearandomintegerbetween1and6.DefResp=MsgBox(MyNum&"Doyouwantanothernumber?",vbYesNo)Loop
DimCheck,CounterCheck=True:Counter=0 'Initializevariables.Do 'Outerloop.DoWhileCounter<20 'Innerloop.Counter=Counter+1 'IncrementCounter.IfCounter=10Then 'IfconditionisTrue...Check=False 'setvalueofflagtoFalse.ExitDo 'Exitinnerloop.EndIfLoopLoopUntilCheck=False 'Exitouterloopimmediately.
Microsoft®VisualBasic®ScriptingEditionEmptyLanguageReference
Version1
SeeAlso
Description
TheEmptykeywordisusedtoindicateanuninitializedvariablevalue.ThisisnotthesamethingasNull.
Microsoft®VisualBasic®ScriptingEditionEqvOperator
LanguageReferenceVersion1
SeeAlso
Description
Performsalogicalequivalenceontwoexpressions.
Syntax
result=expression1Eqvexpression2
TheEqvoperatorsyntaxhastheseparts:
Part Descriptionresult Anynumericvariable.expression1 Anyexpression.expression2 Anyexpression.
Remarks
IfeitherexpressionisNull,resultisalsoNull.WhenneitherexpressionisNull,resultisdeterminedaccordingtothefollowingtable:
Ifexpression1is Andexpression2is TheresultisTrue True TrueTrue False FalseFalse True FalseFalse False True
TheEqvoperatorperformsabitwisecomparisonofidenticallypositionedbitsintwonumericexpressionsandsetsthecorrespondingbitinresultaccordingtothefollowingtable:
Andbitinexpression2is Theresultis
Ifbitinexpression1is
0 0 10 1 01 0 01 1 1
Microsoft®VisualBasic®ScriptingEditionEraseStatement
LanguageReferenceVersion1
SeeAlso
Description
Reinitializestheelementsoffixed-sizearraysanddeallocatesdynamic-arraystoragespace.
Syntax
Erasearray
Thearrayargumentisthenameofthearrayvariabletobeerased.
Remarks
Itisimportanttoknowwhetheranarrayisfixed-size(ordinary)ordynamicbecauseErasebehavesdifferentlydependingonthetypeofarray.Eraserecoversnomemoryforfixed-sizearrays.Erasesetstheelementsofafixedarrayasfollows:
Typeofarray EffectofEraseonfixed-arrayelementsFixednumericarray Setseachelementtozero.
Fixedstringarray Setseachelementtozero-length("").
Arrayofobjects SetseachelementtothespecialvalueNothing.
Erasefreesthememoryusedbydynamicarrays.Beforeyourprogramcanrefertothedynamicarrayagain,itmustredeclarethearrayvariable'sdimensionsusingaReDimstatement.
ThefollowingexampleillustratestheuseoftheErasestatement:
DimNumArray(9)
DimDynamicArray()ReDimDynamicArray(9)'Allocatestoragespace.EraseNumArray'Eachelementisreinitialized.EraseDynamicArray'Freememoryusedbyarray.
Microsoft®VisualBasic®ScriptingEditionErrObject
LanguageReferenceVersion1
SeeAlsoPropertiesMethods
Description
Containsinformationaboutrun-timeerrors.AcceptstheRaiseandClearmethodsforgeneratingandclearingrun-timeerrors.
Remarks
TheErrobjectisanintrinsicobjectwithglobalscope—thereisnoneedtocreateaninstanceofitinyourcode.ThepropertiesoftheErrobjectaresetbythegeneratorofanerror—VisualBasic,anAutomationobject,ortheVBScriptprogrammer.
ThedefaultpropertyoftheErrobjectisNumber.Err.NumbercontainsanintegerandcanbeusedbyanAutomationobjecttoreturnanSCODE.
Whenarun-timeerroroccurs,thepropertiesoftheErrobjectarefilledwithinformationthatuniquelyidentifiestheerrorandinformationthatcanbeusedtohandleit.Togeneratearun-timeerrorinyourcode,usetheRaisemethod.
TheErrobject'spropertiesareresettozeroorzero-lengthstrings("")afteranOnErrorResumeNextstatement.TheClearmethodcanbeusedtoexplicitlyresetErr.
ThefollowingexampleillustratesuseoftheErrobject:
OnErrorResumeNextErr.Raise6'Raiseanoverflowerror.MsgBox("Error#"&CStr(Err.Number)&""&Err.Description)Err.Clear'Cleartheerror.
Microsoft®VisualBasic®ScriptingEditionEvalFunction
LanguageReferenceVersion5
SeeAlso
Description
Evaluatesanexpressionandreturnstheresult.
Syntax
[result=]Eval(expression)
TheEvalfunctionsyntaxhastheseparts:
Part Description
resultOptional.Variabletowhichreturnvalueassignmentismade.Ifresultisnotspecified,considerusingtheExecutestatementinstead.
expression Required.StringcontaininganylegalVBScriptexpression.
Remarks
InVBScript,x=ycanbeinterpretedtwoways.Thefirstisasanassignmentstatement,wherethevalueofyisassignedtox.Thesecondinterpretationisasanexpressionthattestsifxandyhavethesamevalue.Iftheydo,resultisTrue;iftheyarenot,resultisFalse.TheEvalmethodalwaysusesthesecondinterpretation,whereastheExecutestatementalwaysusesthefirst.
NoteInMicrosoft®JScript,noconfusionexistsbetweenassignmentandcomparison,becausetheassignmentoperator(=)isdifferentfromthecomparisonoperator(==).
ThefollowingexampleillustratestheuseoftheEvalfunction:
SubGuessANumberDimGuess,RndNumRndNum=Int((100)*Rnd(1)+1)Guess=CInt(InputBox("Enteryourguess:",,0))DoIfEval("Guess=RndNum")ThenMsgBox"Congratulations!Youguessedit!"ExitSubElseGuess=CInt(InputBox("Sorry!Tryagain.",,0))EndIfLoopUntilGuess=0EndSub
.Microsoft®VisualBasic®ScriptingEdition
ExecuteMethodLanguageReference
Version5
SeeAlsoAppliesto
Description
Executesaregularexpressionsearchagainstaspecifiedstring.
Syntax
object.Execute(string)
TheExecutemethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaRegExpobject.string Required.Thetextstringuponwhichtheregularexpressionisexecuted.
Remarks
TheactualpatternfortheregularexpressionsearchissetusingthePatternpropertyoftheRegExpobject.
TheExecutemethodreturnsaMatchescollectioncontainingaMatchobjectforeachmatchfoundinstring.ExecutereturnsanemptyMatchescollectionifnomatchisfound.
ThefollowingcodeillustratestheuseoftheExecutemethod:
FunctionRegExpTest(patrn,strng)
DimregEx,Match,Matches 'Createvariable.SetregEx=NewRegExp 'Createaregularexpression.regEx.Pattern=patrn 'Setpattern.regEx.IgnoreCase=True 'Setcaseinsensitivity.regEx.Global=True 'Setglobalapplicability.SetMatches=regEx.Execute(strng) 'Executesearch.ForEachMatchinMatches 'IterateMatchescollection.RetStr=RetStr&"Matchfoundatposition"RetStr=RetStr&Match.FirstIndex&".MatchValueis'"RetStr=RetStr&Match.Value&"'."&vbCRLFNextRegExpTest=RetStrEndFunction
MsgBox(RegExpTest("is.","IS1is2IS3is4"))
Microsoft®VisualBasic®ScriptingEditionExecuteStatement
LanguageReferenceVersion5
SeeAlso
Description
Executesoneormorespecifiedstatements.
Syntax
Executestatement
Therequiredstatementargumentisastringexpressioncontainingoneormorestatementsforexecution.Includemultiplestatementsinthestatementargument,usingcolonsorembeddedlinebreakstoseparatethem.
Remarks
InVBScript,x=ycanbeinterpretedtwoways.Thefirstisasanassignmentstatement,wherethevalueofyisassignedtox.Thesecondinterpretationisasanexpressionthattestsifxandyhavethesamevalue.Iftheydo,resultisTrue;iftheyarenot,resultisFalse.TheExecutestatementalwaysusesthefirstinterpretation,whereastheEvalmethodalwaysusesthesecond.
NoteInMicrosoft®JScript�,noconfusionexistsbetweenassignmentandcomparison,becausetheassignmentoperator(=)isdifferentfromthecomparisonoperator(==).
ThecontextinwhichtheExecutestatementisinvokeddetermineswhatobjectsandvariablesareavailabletothecodebeingrun.In-scopeobjectsandvariablesareavailabletocoderunninginanExecutestatement.However,itisimportanttounderstandthatifyouexecutecodethatcreatesaprocedure,thatproceduredoesnotinheritthescopeoftheprocedureinwhichitoccurred.
Likeanyprocedure,thenewprocedure'sscopeisglobal,anditinheritseverythingintheglobalscope.Unlikeanyotherprocedure,itscontextisnotglobalscope,soitcanonlybeexecutedinthecontextoftheprocedurewheretheExecutestatementoccurred.However,ifthesameExecutestatementisinvokedoutsideofaprocedure(i.e.,inglobalscope),notonlydoesitinheriteverythinginglobalscope,butitcanalsobecalledfromanywhere,sinceitscontextisglobal.Thefollowingexampleillustratesthisbehavior:
DimX 'DeclareXinglobalscope.X="Global" 'AssignglobalXavalue.SubProc1 'Declareprocedure.DimX 'DeclareXinlocalscope.X="Local" 'AssignlocalXavalue. 'TheExecutestatementherecreatesa 'procedurethat,wheninvoked,printsX. 'ItprinttheglobalXbecauseProc2 'inheritseverythinginglobalscope.Execute"SubProc2:PrintX:EndSub"PrintEval("X") 'PrintlocalX.Proc2 'InvokeProc2inProc1'sscope.EndSubProc2 'Thislinecausesanerrorsince 'Proc2isunavailableoutsideProc1.Proc1 'InvokeProc1.Execute"SubProc2:PrintX:EndSub"Proc2 'ThisinvocationsucceedsbecauseProc2 'isnowavailableglobally.
ThefollowingexampleshowshowtheExecutestatementcanberewrittensoyoudon'thavetoenclosetheentireprocedureinthequotationmarks:
S="SubProc2"&vbCrLfS=S&"PrintX"&vbCrLfS=S&"EndSub"ExecuteS
Microsoft®VisualBasic®ScriptingEditionExitStatement
LanguageReferenceVersion1
SeeAlso
Description
ExitsablockofDo...Loop,For...Next,Function,orSubcode.
Syntax
ExitDo
ExitFor
ExitFunction
ExitProperty
ExitSub
TheExitstatementsyntaxhastheseforms:
Statement Description
ExitDo
ProvidesawaytoexitaDo...Loopstatement.ItcanbeusedonlyinsideaDo...Loopstatement.ExitDotransferscontroltothestatementfollowingtheLoopstatement.WhenusedwithinnestedDo...Loopstatements,ExitDotransferscontroltotheloopthatisonenestedlevelabovetheloopwhereitoccurs.
ExitFor
ProvidesawaytoexitaForloop.ItcanbeusedonlyinaFor...NextorForEach...Nextloop.ExitFortransferscontroltothestatementfollowingtheNextstatement.WhenusedwithinnestedForloops,ExitFortransferscontroltotheloopthatisonenestedlevelabovetheloopwhereitoccurs.ImmediatelyexitstheFunctionprocedureinwhich
ExitFunction
itappears.ExecutioncontinueswiththestatementfollowingthestatementthatcalledtheFunction.
ExitProperty
ImmediatelyexitsthePropertyprocedureinwhichitappears.ExecutioncontinueswiththestatementfollowingthestatementthatcalledthePropertyprocedure.
ExitSubImmediatelyexitstheSubprocedureinwhichitappears.ExecutioncontinueswiththestatementfollowingthestatementthatcalledtheSub.
ThefollowingexampleillustratestheuseoftheExitstatement:
SubRandomLoopDimI,MyNumDo'Setupinfiniteloop.ForI=1To1000'Loop1000times.MyNum=Int(Rnd*100)'Generaterandomnumbers.SelectCaseMyNum'Evaluaterandomnumber.Case17:MsgBox"Case17"ExitFor'If17,exitFor...Next.Case29:MsgBox"Case29"ExitDo'If29,exitDo...Loop.Case54:MsgBox"Case54"ExitSub'If54,exitSubprocedure.EndSelectNextLoopEndSub
Microsoft®VisualBasic®ScriptingEditionExpFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnse(thebaseofnaturallogarithms)raisedtoapower.
Syntax
Exp(number)
Thenumberargumentcanbeanyvalidnumericexpression.
Remarks
Ifthevalueofnumberexceeds709.782712893,anerroroccurs.Theconstanteisapproximately2.718282.
NoteTheExpfunctioncomplementstheactionoftheLogfunctionandissometimesreferredtoastheantilogarithm.
ThefollowingexampleusestheExpfunctiontoreturneraisedtoapower:
DimMyAngle,MyHSin'Defineangleinradians.MyAngle=1.3'Calculatehyperbolicsine.MyHSin=(Exp(MyAngle)-Exp(-1*MyAngle))/2
Microsoft®VisualBasic®ScriptingEdition^Operator
LanguageReferenceVersion1
SeeAlso
Description
Raisesanumbertothepowerofanexponent.
Syntax
result=number^exponent
The^operatorsyntaxhastheseparts:
Part Descriptionresult Anynumericvariable.number Anynumericexpression.exponent Anynumericexpression.
Remarks
Numbercanbenegativeonlyifexponentisanintegervalue.Whenmorethanoneexponentiationisperformedinasingleexpression,the^operatorisevaluatedasitisencounteredfromlefttoright.
IfeithernumberorexponentisaNullexpression,resultisalsoNull.
Microsoft®VisualBasic®ScriptingEditionFalseLanguageReference
Version1
SeeAlso
Description
TheFalsekeywordhasavalueequalto0.
Microsoft®VisualBasic®ScriptingEditionFilterFunction
LanguageReferenceVersion2
SeeAlso
Description
Returnsazero-basedarraycontainingasubsetofastringarraybasedonaspecifiedfiltercriteria.
Syntax
Filter(InputStrings,Value[,Include[,Compare]])
TheFilterfunctionsyntaxhastheseparts:
Part Description
InputStrings Required.One-dimensionalarrayofstringstobesearched.Value Required.Stringtosearchfor.
Include
Optional.BooleanvalueindicatingwhethertoreturnsubstringsthatincludeorexcludeValue.IfIncludeisTrue,FilterreturnsthesubsetofthearraythatcontainsValueasasubstring.IfIncludeisFalse,FilterreturnsthesubsetofthearraythatdoesnotcontainValueasasubstring.
CompareOptional.Numericvalueindicatingthekindofstringcomparisontouse.SeeSettingssectionforvalues.
Settings
TheCompareargumentcanhavethefollowingvalues:
Constant Value Description
vbBinaryCompare 0 Performabinarycomparison.vbTextCompare 1 Performatextualcomparison.
Remarks
IfnomatchesofValuearefoundwithinInputStrings,Filterreturnsanemptyarray.AnerroroccursifInputStringsisNullorisnotaone-dimensionalarray.
ThearrayreturnedbytheFilterfunctioncontainsonlyenoughelementstocontainthenumberofmatcheditems.
ThefollowingexampleusestheFilterfunctiontoreturnthearraycontainingthesearchcriteria"Mon":
DimMyIndexDimMyArray(3)MyArray(0)="Sunday"MyArray(1)="Monday"MyArray(2)="Tuesday"MyIndex=Filter(MyArray,"Mon")'MyIndex(0)contains"Monday".
Microsoft®VisualBasic®ScriptingEdition
FirstIndexProperty
LanguageReferenceVersion5
SeeAlsoAppliesTo
Description
Returnsthepositioninasearchstringwhereamatchoccurs.
Syntax
object.FirstIndex
TheobjectargumentisalwaysaMatchobject.
Remarks
TheFirstIndexpropertyusesazero-basedoffsetfromthebeginningofthesearchstring.Inotherwords,thefirstcharacterinthestringisidentifiedascharacterzero(0).ThefollowingcodeillustratestheuseoftheFirstIndexproperty:
FunctionRegExpTest(patrn,strng)DimregEx,Match,Matches 'Createvariable.SetregEx=NewRegExp 'Createregularexpression.regEx.Pattern=patrn 'Setpattern.regEx.IgnoreCase=True 'Setcaseinsensitivity.regEx.Global=True 'Setglobalapplicability.SetMatches=regEx.Execute(strng) 'Executesearch.ForEachMatchinMatches 'IterateMatchescollection.RetStr=RetStr&"Match"&I&"foundatposition"RetStr=RetStr&Match.FirstIndex&".MatchValueis"'RetStr=RetStr&Match.Value&"'."&vbCRLF
NextRegExpTest=RetStrEndFunction
MsgBox(RegExpTest("is.","IS1is2IS3is4"))
Microsoft®VisualBasic®ScriptingEditionInt,FixFunctions
LanguageReferenceVersion1
SeeAlso
Description
Returnstheintegerportionofanumber.
Syntax
Int(number)
Fix(number)
Thenumberargumentcanbeanyvalidnumericexpression.IfnumbercontainsNull,Nullisreturned.
Remarks
BothIntandFixremovethefractionalpartofnumberandreturntheresultingintegervalue.
ThedifferencebetweenIntandFixisthatifnumberisnegative,Intreturnsthefirstnegativeintegerlessthanorequaltonumber,whereasFixreturnsthefirstnegativeintegergreaterthanorequaltonumber.Forexample,Intconverts-8.4to-9,andFixconverts-8.4to-8.
Fix(number)isequivalentto:
Sgn(number)*Int(Abs(number))ThefollowingexamplesillustratehowtheIntandFixfunctionsreturnintegerportionsofnumbers:
MyNumber=Int(99.8)'Returns99.MyNumber=Fix(99.2)'Returns99.MyNumber=Int(-99.8)'Returns-100.
MyNumber=Fix(-99.8)'Returns-99.MyNumber=Int(-99.2)'Returns-100.MyNumber=Fix(-99.2)'Returns-99.
Microsoft®VisualBasic®ScriptingEdition
For...NextStatement
LanguageReferenceVersion1
SeeAlso
Description
Repeatsagroupofstatementsaspecifiednumberoftimes.
Syntax
Forcounter=startToend[Stepstep][statements][ExitFor][statements]Next
TheFor...Nextstatementsyntaxhastheseparts:
Part Description
counterNumericvariableusedasaloopcounter.Thevariablecan'tbeanarrayelementoranelementofauser-definedtype.
start Initialvalueofcounter.end Finalvalueofcounter.
step Amountcounterischangedeachtimethroughtheloop.Ifnotspecified,stepdefaultstoone.
statements OneormorestatementsbetweenForandNextthatareexecutedthespecifiednumberoftimes.
Remarks
Thestepargumentcanbeeitherpositiveornegative.Thevalueofthestepargumentdeterminesloopprocessingasfollows:
Value LoopexecutesifPositiveor0 counter<=endNegative counter>=end
Oncetheloopstartsandallstatementsintheloophaveexecuted,stepisaddedtocounter.Atthispoint,eitherthestatementsintheloopexecuteagain(basedonthesametestthatcausedthelooptoexecuteinitially),ortheloopisexitedandexecutioncontinueswiththestatementfollowingtheNextstatement.
TipChangingthevalueofcounterwhileinsidealoopcanmakeitmoredifficulttoreadanddebugyourcode.
ExitForcanonlybeusedwithinaForEach...NextorFor...Nextcontrolstructuretoprovideanalternatewaytoexit.AnynumberofExitForstatementsmaybeplacedanywhereintheloop.ExitForisoftenusedwiththeevaluationofsomecondition(forexample,If...Then),andtransferscontroltothestatementimmediatelyfollowingNext.
YoucannestFor...NextloopsbyplacingoneFor...Nextloopwithinanother.Giveeachloopauniquevariablenameasitscounter.Thefollowingconstructioniscorrect:
ForI=1To10ForJ=1To10ForK=1To10...NextNextNext
Microsoft®VisualBasic®ScriptingEditionForEach...NextStatement
LanguageReferenceVersion2
SeeAlso
Description
Repeatsagroupofstatementsforeachelementinanarrayorcollection.
Syntax
ForEachelementIngroup[statements][ExitFor][statements]Next[element]
TheForEach...Nextstatementsyntaxhastheseparts:
Part Description
element
Variableusedtoiteratethroughtheelementsofthecollectionorarray.Forcollections,elementcanonlybeaVariantvariable,agenericObjectvariable,oranyspecificAutomationobjectvariable.Forarrays,elementcanonlybeaVariantvariable.
group Nameofanobjectcollectionorarray.
statements Oneormorestatementsthatareexecutedoneachitemingroup.
Remarks
TheForEachblockisenteredifthereisatleastoneelementingroup.
Oncetheloophasbeenentered,allthestatementsintheloopareexecutedforthefirstelementingroup.Aslongastherearemoreelementsingroup,thestatementsintheloopcontinuetoexecuteforeachelement.Whentherearenomoreelementsingroup,theloopisexitedandexecutioncontinueswiththestatementfollowingtheNextstatement.
TheExitForcanonlybeusedwithinaForEach...NextorFor...Nextcontrolstructuretoprovideanalternatewaytoexit.AnynumberofExitForstatementsmaybeplacedanywhereintheloop.TheExitForisoftenusedwiththeevaluationofsomecondition(forexample,If...Then),andtransferscontroltothestatementimmediatelyfollowingNext.
YoucannestForEach...NextloopsbyplacingoneForEach...Nextloopwithinanother.However,eachloopelementmustbeunique.
NoteIfyouomitelementinaNextstatement,executioncontinuesasifyouhadincludedit.IfaNextstatementisencounteredbeforeitscorrespondingForstatement,anerroroccurs.
ThefollowingexampleillustratesuseoftheForEach...Nextstatement:
FunctionShowFolderList(folderspec)Dimfso,f,f1,fc,sSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFolder(folderspec)Setfc=f.FilesForEachf1infcs=s&f1.names=s&"<BR>"NextShowFolderList=sEndFunction
Microsoft®VisualBasic®ScriptingEdition
FormatCurrencyFunction
LanguageReferenceVersion2
SeeAlso
Description
Returnsanexpressionformattedasacurrencyvalueusingthecurrencysymboldefinedinthesystemcontrolpanel.
Syntax
FormatCurrency(Expression[,NumDigitsAfterDecimal[,IncludeLeadingDigit[,UseParensForNegativeNumbers[,GroupDigits]]]])
TheFormatCurrencyfunctionsyntaxhastheseparts:
Part Description
Expression Required.Expressiontobeformatted.
NumDigitsAfterDecimal
Optional.Numericvalueindicatinghowmanyplacestotherightofthedecimalaredisplayed.Defaultvalueis-1,whichindicatesthatthecomputer'sregionalsettingsareused.
IncludeLeadingDigit
Optional.Tristateconstantthatindicateswhetherornotaleadingzeroisdisplayedforfractionalvalues.SeeSettingssectionforvalues.Optional.Tristateconstantthatindicateswhetherornotto
UseParensForNegativeNumbers placenegativevalueswithinparentheses.SeeSettingssectionforvalues.
GroupDigits
Optional.Tristateconstantthatindicateswhetherornotnumbersaregroupedusingthegroupdelimiterspecifiedinthecomputer'sregionalsettings.SeeSettingssectionforvalues.
Settings
TheIncludeLeadingDigit,UseParensForNegativeNumbers,andGroupDigitsargumentshavethefollowingsettings:
Constant Value DescriptionTristateTrue -1 TrueTristateFalse 0 False
TristateUseDefault -2 Usethesettingfromthecomputer'sregionalsettings.
Remarks
Whenoneormoreoptionalargumentsareomitted,valuesforomittedargumentsareprovidedbythecomputer'sregionalsettings.Thepositionofthecurrencysymbolrelativetothecurrencyvalueisdeterminedbythesystem'sregionalsettings.
NoteAllsettingsinformationcomesfromtheRegionalSettingsCurrencytab,exceptleadingzerowhichcomesfromtheNumbertab.
ThefollowingexampleusestheFormatCurrencyfunctiontoformattheexpressionasacurrencyandassignittoMyCurrency:
DimMyCurrencyMyCurrency=FormatCurrency(1000)'MyCurrencycontains$1000.00.
Microsoft®VisualBasic®ScriptingEdition
FormatDateTimeFunction
LanguageReferenceVersion2
SeeAlso
Description
Returnsanexpressionformattedasadateortime.
Syntax
FormatDateTime(Date[,NamedFormat])
TheFormatDateTimefunctionsyntaxhastheseparts:
Part DescriptionDate Required.Dateexpressiontobeformatted.
NamedFormatOptional.Numericvaluethatindicatesthedate/timeformatused.Ifomitted,vbGeneralDateisused.
Settings
TheNamedFormatargumenthasthefollowingsettings:
Constant Value Description
vbGeneralDate 0
Displayadateand/ortime.Ifthereisadatepart,displayitasashortdate.Ifthereisatimepart,displayitasalongtime.Ifpresent,bothpartsaredisplayed.
vbLongDate 1Displayadateusingthelongdateformatspecifiedinyourcomputer'sregionalsettings.Displayadateusingtheshortdate
vbShortDate 2 formatspecifiedinyourcomputer'sregionalsettings.
vbLongTime 3Displayatimeusingthetimeformatspecifiedinyourcomputer'sregionalsettings.
vbShortTime 4 Displayatimeusingthe24-hourformat(hh:mm).
Remarks
ThefollowingexampleusestheFormatDateTimefunctiontoformattheexpressionasalongdateandassignittoMyDateTime:
FunctionGetCurrentDate'FormatDateTimeformatsDateinlongdate.GetCurrentDate=FormatDateTime(Date,1)EndFunction
Microsoft®VisualBasic®ScriptingEdition
FormatNumberFunction
LanguageReferenceVersion2
SeeAlso
Description
Returnsanexpressionformattedasanumber.
Syntax
FormatNumber(Expression[,NumDigitsAfterDecimal[,IncludeLeadingDigit[,UseParensForNegativeNumbers[,GroupDigits]]]])
TheFormatNumberfunctionsyntaxhastheseparts:
Part Description
Expression Required.Expressiontobeformatted.
NumDigitsAfterDecimal
Optional.Numericvalueindicatinghowmanyplacestotherightofthedecimalaredisplayed.Defaultvalueis-1,whichindicatesthatthecomputer'sregionalsettingsareused.
IncludeLeadingDigit
Optional.Tristateconstantthatindicateswhetherornotaleadingzeroisdisplayedforfractionalvalues.SeeSettingssectionforvalues.
UseParensForNegativeNumbers
Optional.Tristateconstantthatindicateswhetherornottoplacenegativevalueswithin
parentheses.SeeSettingssectionforvalues.
GroupDigits
Optional.Tristateconstantthatindicateswhetherornotnumbersaregroupedusingthegroupdelimiterspecifiedinthecontrolpanel.SeeSettingssectionforvalues.
Settings
TheIncludeLeadingDigit,UseParensForNegativeNumbers,andGroupDigitsargumentshavethefollowingsettings:
Constant Value DescriptionTristateTrue -1 TrueTristateFalse 0 False
TristateUseDefault -2 Usethesettingfromthecomputer'sregionalsettings.
Remarks
Whenoneormoreoftheoptionalargumentsareomitted,thevaluesforomittedargumentsareprovidedbythecomputer'sregionalsettings.
NoteAllsettingsinformationcomesfromtheRegionalSettingsNumbertab.
ThefollowingexampleusestheFormatNumberfunctiontoformatanumbertohavefourdecimalplaces:
FunctionFormatNumberDemo
DimMyAngle,MySecant,MyNumberMyAngle=1.3'Defineangleinradians.MySecant=1/Cos(MyAngle)'Calculatesecant.FormatNumberDemo=FormatNumber(MySecantEndFunction
Microsoft®VisualBasic®ScriptingEdition
FormatPercentFunction
LanguageReferenceVersion2
SeeAlso
Description
Returnsanexpressionformattedasapercentage(multipliedby100)withatrailing%character.
Syntax
FormatPercent(Expression[,NumDigitsAfterDecimal[,IncludeLeadingDigit[,UseParensForNegativeNumbers[,GroupDigits]]]])
TheFormatPercentfunctionsyntaxhastheseparts:
Part Description
Expression Required.Expressiontobeformatted.
NumDigitsAfterDecimal
Optional.Numericvalueindicatinghowmanyplacestotherightofthedecimalaredisplayed.Defaultvalueis-1,whichindicatesthatthecomputer'sregionalsettingsareused.
IncludeLeadingDigit
Optional.Tristateconstantthatindicateswhetherornotaleadingzeroisdisplayedforfractionalvalues.SeeSettingssectionforvalues.Optional.Tristateconstantthatindicateswhetherornotto
UseParensForNegativeNumbers placenegativevalueswithinparentheses.SeeSettingssectionforvalues.
GroupDigits
Optional.Tristateconstantthatindicateswhetherornotnumbersaregroupedusingthegroupdelimiterspecifiedinthecontrolpanel.SeeSettingssectionforvalues.
Settings
TheIncludeLeadingDigit,UseParensForNegativeNumbers,andGroupDigitsargumentshavethefollowingsettings:
Constant Value DescriptionTristateTrue -1 TrueTristateFalse 0 False
TristateUseDefault -2 Usethesettingfromthecomputer'sregionalsettings.
Remarks
Whenoneormoreoptionalargumentsareomitted,thevaluesfortheomittedargumentsareprovidedbythecomputer'sregionalsettings.
NoteAllsettingsinformationcomesfromtheRegionalSettingsNumbertab.
ThefollowingexampleusestheFormatPercentfunctiontoformatanexpressionasapercent:
DimMyPercentMyPercent=FormatPercent(2/32)'MyPercentcontains6.25%.
Microsoft®VisualBasic®ScriptingEdition
FunctionStatement
LanguageReferenceVersion1
SeeAlso
Description
Declaresthename,arguments,andcodethatformthebodyofaFunctionprocedure.
Syntax
[Public[Default]|Private]Functionname[(arglist)][statements][name=expression][ExitFunction][statements][name=expression]EndFunction
TheFunctionstatementsyntaxhastheseparts:
Part Description
Public IndicatesthattheFunctionprocedureisaccessibletoallotherproceduresinallscripts.
DefaultUsedonlywiththePublickeywordinaClassblocktoindicatethattheFunctionprocedureisthedefaultmethodfortheclass.AnerroroccursifmorethanoneDefaultprocedureisspecifiedinaclass.
PrivateIndicatesthattheFunctionprocedureisaccessibleonlytootherproceduresinthescriptwhereitisdeclaredorifthefunctionisamemberofaclass,andthattheFunctionprocedureisaccessibleonlytootherproceduresinthatclass.
name NameoftheFunction;followsstandardvariablenamingconventions.
arglist ListofvariablesrepresentingargumentsthatarepassedtotheFunctionprocedurewhenitiscalled.Multiplevariablesareseparatedbycommas.
statements AnygroupofstatementstobeexecutedwithinthebodyoftheFunctionprocedure.expression ReturnvalueoftheFunction.
Thearglistargumenthasthefollowingsyntaxandparts:
[ByVal|ByRef]varname[()]
Part DescriptionByVal Indicatesthattheargumentispassedbyvalue.
ByRef Indicatesthattheargumentispassedbyreference.
varname Nameofthevariablerepresentingtheargument;followsstandardvariablenamingconventions.
Remarks
IfnotexplicitlyspecifiedusingeitherPublicorPrivate,Functionproceduresarepublicbydefault,thatis,theyarevisibletoallotherproceduresinyourscript.ThevalueoflocalvariablesinaFunctionisnotpreservedbetweencallstotheprocedure.
Youcan'tdefineaFunctionprocedureinsideanyotherprocedure(e.g.SuborPropertyGet).
TheExitFunctionstatementcausesanimmediateexitfromaFunctionprocedure.ProgramexecutioncontinueswiththestatementthatfollowsthestatementthatcalledtheFunctionprocedure.AnynumberofExitFunctionstatementscanappearanywhereinaFunctionprocedure.
LikeaSubprocedure,aFunctionprocedureisaseparateprocedurethatcantakearguments,performaseriesofstatements,andchangethevaluesofitsarguments.However,unlikeaSubprocedure,youcanuseaFunctionprocedureontherightsideofanexpressioninthesamewayyouuseany
intrinsicfunction,suchasSqr,Cos,orChr,whenyouwanttousethevaluereturnedbythefunction.
YoucallaFunctionprocedureusingthefunctionname,followedbytheargumentlistinparentheses,inanexpression.SeetheCallstatementforspecificinformationonhowtocallFunctionprocedures.
CautionFunctionprocedurescanberecursive,thatis,theycancallthemselvestoperformagiventask.However,recursioncanleadtostackoverflow.
Toreturnavaluefromafunction,assignthevaluetothefunctionname.Anynumberofsuchassignmentscanappearanywherewithintheprocedure.Ifnovalueisassignedtoname,theprocedurereturnsadefaultvalue:anumericfunctionreturns0andastringfunctionreturnsazero-lengthstring("").AfunctionthatreturnsanobjectreferencereturnsNothingifnoobjectreferenceisassignedtoname(usingSet)withintheFunction.
ThefollowingexampleshowshowtoassignareturnvaluetoafunctionnamedBinarySearch.Inthiscase,Falseisassignedtothenametoindicatethatsomevaluewasnotfound.
FunctionBinarySearch(...)...'Valuenotfound.ReturnavalueofFalse.Iflower>upperThenBinarySearch=FalseExitFunctionEndIf...EndFunction
VariablesusedinFunctionproceduresfallintotwocategories:thosethatareexplicitlydeclaredwithintheprocedureandthosethatarenot.Variablesthatareexplicitlydeclaredinaprocedure(usingDimortheequivalent)arealwayslocaltotheprocedure.Variablesthatareusedbutnotexplicitlydeclaredinaprocedurearealsolocalunlesstheyareexplicitlydeclaredatsomehigherleveloutsidetheprocedure.
CautionAprocedurecanuseavariablethatisnotexplicitlydeclaredintheprocedure,butanamingconflictcanoccurifanythingyouhavedefinedatthescriptlevelhasthesamename.Ifyourprocedurereferstoanundeclaredvariablethathasthesamenameasanotherprocedure,constant,orvariable,itisassumedthatyourprocedureisreferringtothatscript-levelname.Toavoidthiskindofconflict,useanOptionExplicitstatementtoforceexplicitdeclarationofvariables.
CautionVBScriptmayrearrangearithmeticexpressionstoincreaseinternalefficiency.AvoidusingaFunctionprocedureinanarithmeticexpressionwhenthefunctionchangesthevalueofvariablesinthesameexpression.
Microsoft®VisualBasic®ScriptingEdition
GetObjectFunction
LanguageReferenceVersion2
SeeAlso
Description
ReturnsareferencetoanAutomationobjectfromafile.
Syntax
GetObject([pathname][,class])
TheGetObjectfunctionsyntaxhastheseparts:
Part Description
pathnameOptional;String.Fullpathandnameofthefilecontainingtheobjecttoretrieve.Ifpathnameisomitted,classisrequired.
class Optional;String.Classoftheobject.
Theclassargumentusesthesyntaxappname.objectypeandhastheseparts:
Part Description
appname Required;String.Nameoftheapplicationprovidingtheobject.
objectype Required;String.Typeorclassofobjecttocreate.
Remarks
UsetheGetObjectfunctiontoaccessanAutomationobjectfromafileandassigntheobjecttoanobjectvariable.UsetheSetstatementtoassigntheobjectreturnedbyGetObjecttotheobjectvariable.Forexample:
DimCADObjectSetCADObject=GetObject("C:\CAD\SCHEMA.CAD"
Whenthiscodeisexecuted,theapplicationassociatedwiththespecifiedpathnameisstartedandtheobjectinthespecifiedfileisactivated.Ifpathnameisazero-lengthstring(""),GetObjectreturnsanewobjectinstanceofthespecifiedtype.Ifthepathnameargumentisomitted,GetObjectreturnsacurrentlyactiveobjectofthespecifiedtype.Ifnoobjectofthespecifiedtypeexists,anerroroccurs.
Someapplicationsallowyoutoactivatepartofafile.Addanexclamationpoint(!)totheendofthefilenameandfollowitwithastringthatidentifiesthepartofthefileyouwanttoactivate.Forinformationonhowtocreatethisstring,seethedocumentationfortheapplicationthatcreatedtheobject.
Forexample,inadrawingapplicationyoumighthavemultiplelayerstoadrawingstoredinafile.YoucouldusethefollowingcodetoactivatealayerwithinadrawingcalledSCHEMA.CAD:
SetLayerObject=GetObject("C:\CAD\SCHEMA.Ifyoudon'tspecifytheobject'sclass,Automationdeterminestheapplicationtostartandtheobjecttoactivate,basedonthefilenameyouprovide.Somefiles,however,maysupportmorethanoneclassofobject.Forexample,adrawingmightsupportthreedifferenttypesofobjects:anApplicationobject,aDrawingobject,andaToolbarobject,allofwhicharepartofthesamefile.Tospecifywhichobjectinafileyouwanttoactivate,usetheoptionalclassargument.Forexample:
DimMyObjectSetMyObject=GetObject("C:\DRAWINGS\SAMPLE.DRW","FIGMENT.DRAWING"
Intheprecedingexample,FIGMENTisthenameofadrawingapplicationandDRAWINGisoneoftheobjecttypesitsupports.Onceanobjectisactivated,youreferenceitincodeusingtheobjectvariableyoudefined.Intheprecedingexample,youaccesspropertiesandmethodsofthenew
objectusingtheobjectvariableMyObject.Forexample:
MyObject.Line9,90MyObject.InsertText9,100,"Hello,world."MyObject.SaveAs"C:\DRAWINGS\SAMPLE.DRW"
NoteUsetheGetObjectfunctionwhenthereisacurrentinstanceoftheobjectorifyouwanttocreatetheobjectwithafilealreadyloaded.Ifthereisnocurrentinstance,andyoudon'twanttheobjectstartedwithafileloaded,usetheCreateObjectfunction.
Ifanobjecthasregistereditselfasasingle-instanceobject,onlyoneinstanceoftheobjectiscreated,nomatterhowmanytimesCreateObjectisexecuted.Withasingle-instanceobject,GetObjectalwaysreturnsthesameinstancewhencalledwiththezero-lengthstring("")syntax,anditcausesanerrorifthepathnameargumentisomitted.
Microsoft®VisualBasic®ScriptingEditionGetRefFunction
LanguageReferenceVersion5
SeeAlso
Description
Returnsareferencetoaprocedurethatcanbeboundtoanevent.
Syntax
Setobject.eventname=GetRef(procname)
TheGetReffunctionsyntaxhastheseparts:
Part Description
object Required.Nameoftheobjectwithwhicheventisassociated.
event Required.Nameoftheeventtowhichthefunctionistobebound.
procname Required.StringcontainingthenameoftheSuborFunctionprocedurebeingassociatedwiththeevent.
Remarks
TheGetReffunctionallowsyoutoconnectaVBScriptprocedure(FunctionorSub)toanyavailableeventonyourDHTML(DynamicHTML)pages.TheDHTMLobjectmodelprovidesinformationaboutwhateventsareavailableforitsvariousobjects.
Inotherscriptingandprogramminglanguages,thefunctionalityprovidedbyGetRefisreferredtoasafunctionpointer,thatis,itpointstotheaddressofaproceduretobeexecutedwhenthespecifiedeventoccurs.
ThefollowingexampleillustratestheuseoftheGetReffunction:
<SCRIPTLANGUAGE="VBScript">
FunctionGetRefTest()DimSplashSplash="GetRefTestVersion1.0"&vbCrLfSplash=Splash&Chr(169)&"YourCompany1999"MsgBoxSplashEndFunction
SetWindow.Onload=GetRef("GetRefTest")
</SCRIPT>
Microsoft®VisualBasic®ScriptingEdition
GlobalPropertyLanguageReference
Version5
SeeAlsoAppliesTo
Description
SetsorreturnsaBooleanvaluethatindicatesifapatternshouldmatchalloccurrencesinanentiresearchstringorjustthefirstone.
Syntax
object.Global[=True|False]
TheobjectargumentisalwaysaRegExpobject.ThevalueoftheGlobalpropertyisTrueifthesearchappliestotheentirestring,Falseifitdoesnot.DefaultisFalse.
Remarks
ThefollowingcodeillustratestheuseoftheGlobalproperty(changethevalueassignedtoGlobalpropertytoseeitseffect):
FunctionRegExpTest(patrn,strng)DimregEx,Match,Matches 'Createvariable.SetregEx=NewRegExp 'Createaregularexpression.regEx.Pattern=patrn 'Setpattern.regEx.IgnoreCase=True 'Setcaseinsensitivity.regEx.Global=True 'Setglobalapplicability.SetMatches=regEx.Execute(strng) 'Executesearch.
ForEachMatchinMatches 'IterateMatchescollection.RetStr=RetStr&"Matchfoundatposition"RetStr=RetStr&Match.FirstIndex&".MatchValueis'"RetStr=RetStr&Match.Value&"'."&vbCRLFNextRegExpTest=RetStrEndFunction
MsgBox(RegExpTest("is.","IS1is2IS3is4"))
Microsoft®VisualBasic®ScriptingEditionHexFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsastringrepresentingthehexadecimalvalueofanumber.
Syntax
Hex(number)
Thenumberargumentisanyvalidexpression.
Remarks
Ifnumberisnotalreadyawholenumber,itisroundedtothenearestwholenumberbeforebeingevaluated.
Ifnumberis HexreturnsNull Null.Empty Zero(0).Anyothernumber Uptoeighthexadecimalcharacters.
Youcanrepresenthexadecimalnumbersdirectlybyprecedingnumbersintheproperrangewith&H.Forexample,&H10representsdecimal16inhexadecimalnotation.
ThefollowingexampleusestheHexfunctiontoreturnthehexadecimalvalueofanumber:
DimMyHexMyHex=Hex(5)'Returns5.MyHex=Hex(10)'ReturnsA.MyHex=Hex(459)'Returns1CB.
Microsoft®VisualBasic®ScriptingEdition
HelpContextProperty
LanguageReferenceVersion2
SeeAlsoAppliesto
Description
SetsorreturnsacontextIDforatopicinaHelpFile.
Syntax
object.HelpContext[=contextID]
TheHelpContextpropertysyntaxhastheseparts:
Part Descriptionobject Required.AlwaystheErrobject.
contextID Optional.AvalididentifierforaHelptopicwithintheHelpfile.
Remarks
IfaHelpfileisspecifiedinHelpFile,theHelpContextpropertyisusedtoautomaticallydisplaytheHelptopicidentified.IfbothHelpFileandHelpContextareempty,thevalueoftheNumberpropertyischecked.IfitcorrespondstoaVBScriptrun-timeerrorvalue,thentheVBScriptHelpcontextIDfortheerrorisused.IftheNumberpropertydoesn'tcorrespondtoaVBScripterror,thecontentsscreenfortheVBScriptHelpfileisdisplayed.
ThefollowingexampleillustratesuseoftheHelpContextproperty:
OnErrorResumeNextDimMsgErr.Clear
Err.Raise6'Generate"Overflow"error.Err.Helpfile="yourHelp.hlp"Err.HelpContext=yourContextIDIfErr.Number<>0ThenMsg="PressF1orHelptosee"&Err.Helpfile&"topicfor"&_"thefollowingHelpContext:"&Err.HelpContextMsgBoxMsg,,"error:"&Err.Description,Err.Helpfile,Err.HelpContextEndIf
Microsoft®VisualBasic®ScriptingEdition
HelpFilePropertyLanguageReference
Version2
SeeAlsoAppliesto
Description
SetsorreturnsafullyqualifiedpathtoaHelpFile.
Syntax
object.HelpFile[=contextID]
TheHelpFilepropertysyntaxhastheseparts:
Part Descriptionobject Required.AlwaystheErrobject.contextID Optional.FullyqualifiedpathtotheHelpfile.
Remarks
IfaHelpfileisspecifiedinHelpFile,itisautomaticallycalledwhentheuserclickstheHelpbutton(orpressestheF1key)intheerrormessagedialogbox.IftheHelpContextpropertycontainsavalidcontextIDforthespecifiedfile,thattopicisautomaticallydisplayed.IfnoHelpFileisspecified,theVBScriptHelpfileisdisplayed.
OnErrorResumeNextDimMsgErr.ClearErr.Raise6'Generate"Overflow"error.Err.Helpfile="yourHelp.hlp"Err.HelpContext=yourContextIDIfErr.Number<>0ThenMsg="PressF1orHelptosee"&Err.Helpfile&"topicfor"&_
"thefollowingHelpContext:"&Err.HelpContextMsgBoxMsg,,"error:"&Err.Description,Err.Helpfile,Err.HelpContextEndIf
Microsoft®VisualBasic®ScriptingEditionHourFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsawholenumberbetween0and23,inclusive,representingthehouroftheday.
Syntax
Hour(time)
Thetimeargumentisanyexpressionthatcanrepresentatime.IftimecontainsNull,Nullisreturned.
ThefollowingexampleusestheHourfunctiontoobtainthehourfromthecurrenttime:
DimMyTime,MyHourMyTime=NowMyHour=Hour(MyTime)'MyHourcontainsthenumberrepresenting'thecurrenthour.
Microsoft®VisualBasic®ScriptingEdition
If...Then...ElseStatement
LanguageReferenceVersion1
Description
Conditionallyexecutesagroupofstatements,dependingonthevalueofanexpression.
Syntax
IfconditionThenstatements[Elseelsestatements]
Or,youcanusetheblockformsyntax:
IfconditionThen[statements][ElseIfcondition-nThen[elseifstatements]]...[Else[elsestatements]]EndIf
TheIf...Then...Elsestatementsyntaxhastheseparts:
Part Description
condition
Oneormoreofthefollowingtwotypesofexpressions:
AnumericorstringexpressionthatevaluatestoTrueorFalse.IfconditionisNull,conditionistreatedasFalse.
AnexpressionoftheformTypeOfobjectnameIsobjecttype.Theobjectnameisanyobjectreferenceandobjecttypeisanyvalidobjecttype.TheexpressionisTrueifobjectnameisoftheobjecttypespecifiedbyobjecttype;otherwiseitisFalse.
statementsOneormorestatementsseparatedbycolons;executedifconditionisTrue.condition-nSameascondition.elseifstatementsOneormorestatementsexecutediftheassociatedcondition-nisTrue.elsestatementsOneormorestatementsexecutedifnopreviousconditionorcondition-nexpressionisTrue.
Remarks
Youcanusethesingle-lineform(firstsyntax)forshort,simpletests.However,theblockform(secondsyntax)providesmorestructureandflexibilitythanthesingle-lineformandisusuallyeasiertoread,maintain,anddebug.
NoteWiththesingle-linesyntax,itispossibletohavemultiplestatementsexecutedastheresultofanIf...Thendecision,buttheymustallbeonthesamelineandseparatedbycolons,asinthefollowingstatement:
IfA>10ThenA=A+1:B=B+A:C=C+B
WhenexecutingablockIf(secondsyntax),conditionistested.IfconditionisTrue,thestatementsfollowingThenareexecuted.IfconditionisFalse,eachElseIf(ifany)isevaluatedinturn.WhenaTrueconditionisfound,thestatementsfollowingtheassociatedThenareexecuted.IfnoneoftheElseIfstatementsareTrue(ortherearenoElseIfclauses),thestatementsfollowingElseareexecuted.AfterexecutingthestatementsfollowingThenorElse,executioncontinueswiththestatementfollowingEndIf.
TheElseandElseIfclausesarebothoptional.YoucanhaveasmanyElseIfstatementsasyouwantinablockIf,butnonecanappearaftertheElseclause.BlockIfstatementscanbenested;thatis,containedwithinoneanother.
WhatfollowstheThenkeywordisexaminedtodeterminewhetherornotastatementisablockIf.IfanythingotherthanacommentappearsafterThenonthesameline,thestatementistreatedasasingle-lineIfstatement.
AblockIfstatementmustbethefirststatementonaline.TheblockIfmustendwithanEndIfstatement.
Microsoft®VisualBasic®ScriptingEdition
IgnoreCaseProperty
LanguageReferenceVersion5
SeeAlsoAppliesTo
Description
SetsorreturnsaBooleanvaluethatindicatesifapatternsearchiscase-sensitiveornot.
Syntax
object.IgnoreCase[=True|False]
TheobjectargumentisalwaysaRegExpobject.ThevalueoftheIgnoreCasepropertyisFalseifthesearchiscase-sensitive,Trueifitisnot.DefaultisFalse.
Remarks
ThefollowingcodeillustratestheuseoftheIgnoreCaseproperty(changethevalueassignedtoIgnoreCasepropertytoseeitseffect):
FunctionRegExpTest(patrn,strng)DimregEx,Match,Matches 'Createvariable.SetregEx=NewRegExp 'Createaregularexpression.regEx.Pattern=patrn 'Setpattern.regEx.IgnoreCase=True 'Setcaseinsensitivity.
regEx.Global=True 'Setglobalapplicability.SetMatches=regEx.Execute(strng) 'Executesearch.ForEachMatchinMatches 'IterateMatchescollection.RetStr=RetStr&"Matchfoundatposition"RetStr=RetStr&Match.FirstIndex&".MatchValueis'"RetStr=RetStr&Match.Value&"'."&vbCRLFNextRegExpTest=RetStrEndFunction
MsgBox(RegExpTest("is.","IS1is2IS3is4"))
Microsoft®VisualBasic®ScriptingEditionImpOperator
LanguageReferenceVersion1
SeeAlso
Description
Performsalogicalimplicationontwoexpressions.
Syntax
result=expression1Impexpression2
TheImpoperatorsyntaxhastheseparts:
Part Descriptionresult Anynumericvariable.expression1 Anyexpression.expression2 Anyexpression.
Remarks
Thefollowingtableillustrateshowresultisdetermined:
Ifexpression1is Andexpression2is ThenresultisTrue True TrueTrue False FalseTrue Null NullFalse True TrueFalse False TrueFalse Null TrueNull True TrueNull False Null
Null Null Null
TheImpoperatorperformsabitwisecomparisonofidenticallypositionedbitsintwonumericexpressionsandsetsthecorrespondingbitinresultaccordingtothefollowingtable:
Ifbitinexpression1is Andbitinexpression2is Thenresultis
0 0 10 1 11 0 01 1 1
Microsoft®VisualBasic®ScriptingEdition
InitializeEventLanguageReference
Version5
SeeAlsoAppliesTo
Description
Occurswhenaninstanceoftheassociatedclassiscreated.
Syntax
PrivateSubClass_Initialize()statementsEndSub
Thestatementspartconsistsofzeroormorecodestatementstoberunwhentheclassisinitlized.
Remarks
ThefollowingexampleillustratestheuseoftheInitializeevent:
ClassTestClassPrivateSubClass_Initialize 'SetupInitializeevent.MsgBox("TestClassstarted")EndSubPrivateSubClass_Terminate 'SetupTerminateevent.MsgBox("TestClassterminated")EndSubEndClass
SetX=NewTestClass 'CreateaninstanceofTestClass.
SetX=Nothing 'Destroytheinstance.
Microsoft®VisualBasic®ScriptingEdition
InputBoxFunctionLanguageReference
Version1
SeeAlso
Description
Displaysapromptinadialogbox,waitsfortheusertoinputtextorclickabutton,andreturnsthecontentsofthetextbox.
Syntax
InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])
TheInputBoxfunctionsyntaxhasthesearguments:
Part Description
prompt
Stringexpressiondisplayedasthemessageinthedialogbox.Themaximumlengthofpromptisapproximately1024characters,dependingonthewidthofthecharactersused.Ifpromptconsistsofmorethanoneline,youcanseparatethelinesusingacarriagereturncharacter(Chr(13)),alinefeedcharacter(Chr(10)),orcarriagereturn–linefeedcharactercombination(Chr(13)&Chr(10))betweeneachline.
titleStringexpressiondisplayedinthetitlebarofthedialogbox.Ifyouomittitle,theapplicationnameisplacedinthetitlebar.
defaultStringexpressiondisplayedinthetextboxasthedefaultresponseifnootherinputisprovided.Ifyouomitdefault,thetextboxisdisplayedempty.
xpos
Numericexpressionthatspecifies,intwips,thehorizontaldistanceoftheleftedgeofthedialogboxfromtheleftedgeofthescreen.Ifxposisomitted,thedialogboxishorizontallycentered.Numericexpressionthatspecifies,intwips,thevertical
yposdistanceoftheupperedgeofthedialogboxfromthetopofthescreen.Ifyposisomitted,thedialogboxisverticallypositionedapproximatelyone-thirdofthewaydownthescreen.
helpfileStringexpressionthatidentifiestheHelpfiletousetoprovidecontext-sensitiveHelpforthedialogbox.Ifhelpfileisprovided,contextmustalsobeprovided.
context
NumericexpressionthatidentifiestheHelpcontextnumberassignedbytheHelpauthortotheappropriateHelptopic.Ifcontextisprovided,helpfilemustalsobeprovided.
Remarks
Whenbothhelpfileandcontextaresupplied,aHelpbuttonisautomaticallyaddedtothedialogbox.
IftheuserclicksOKorpressesENTER,theInputBoxfunctionreturnswhateverisinthetextbox.IftheuserclicksCancel,thefunctionreturnsazero-lengthstring("").
ThefollowingexampleusestheInputBoxfunctiontodisplayaninputboxandassignthestringtothevariableInput:
DimInputInput=InputBox("Enteryourname")MsgBox("Youentered:"&Input)
Microsoft®VisualBasic®ScriptingEditionInStrFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsthepositionofthefirstoccurrenceofonestringwithinanother.
Syntax
InStr([start,]string1,string2[,compare])
TheInStrfunctionsyntaxhasthesearguments:
Part Description
start
Optional.Numericexpressionthatsetsthestartingpositionforeachsearch.Ifomitted,searchbeginsatthefirstcharacterposition.IfstartcontainsNull,anerroroccurs.Thestartargumentisrequiredifcompareisspecified.
string1 Required.Stringexpressionbeingsearched.string2 Required.Stringexpressionsearchedfor.
compare
Optional.Numericvalueindicatingthekindofcomparisontousewhenevaluatingsubstrings.SeeSettingssectionforvalues.Ifomitted,abinarycomparisonisperformed.
Settings
Thecompareargumentcanhavethefollowingvalues:
Constant Value DescriptionvbBinaryCompare 0 Performabinarycomparison.vbTextCompare 1 Performatextualcomparison.
ReturnValues
TheInStrfunctionreturnsthefollowingvalues:
If InStrreturnsstring1iszero-length 0string1isNull Nullstring2iszero-length startstring2isNull Nullstring2isnotfound 0string2isfoundwithinstring1 Positionatwhichmatchisfoundstart>Len(string2) 0
Remarks
ThefollowingexamplesuseInStrtosearchastring:
DimSearchString,SearchChar,MyPosSearchString="XXpXXpXXPXXP" 'Stringtosearchin.SearchChar="P" 'Searchfor"P".MyPos=Instr(4,SearchString,SearchChar,1) 'Atextualcomparisonstartingat 'position4.Returns6.MyPos=Instr(1,SearchString,SearchChar,0) 'Abinarycomparisonstartingat 'position1.Returns9.MyPos=Instr(SearchString,SearchChar) 'Comparisonisbinarybydefault
'(lastargumentisomitted). 'Returns9.MyPos=Instr(1,SearchString,"W") 'Abinarycomparisonstartingatposition1. 'Returns0("W"isnotfound).
NoteTheInStrBfunctionisusedwithbytedatacontainedinastring.Insteadofreturningthecharacterpositionofthefirstoccurrenceofonestringwithinanother,InStrBreturnsthebyteposition.
Microsoft®VisualBasic®ScriptingEdition\Operator
LanguageReferenceVersion1
SeeAlso
Description
Dividestwonumbersandreturnsanintegerresult.
Syntax
result=number1\number2
The\operatorsyntaxhastheseparts:
Part Descriptionresult Anynumericvariable.number1 Anynumericexpression.number2 Anynumericexpression.
Remarks
Beforedivisionisperformed,numericexpressionsareroundedtoByte,Integer,orLongsubtypeexpressions.
IfanyexpressionisNull,resultisalsoNull.AnyexpressionthatisEmptyistreatedas0.
Microsoft®VisualBasic®ScriptingEditionIsOperator
LanguageReferenceVersion1
SeeAlso
Description
Comparestwoobjectreferencevariables.
Syntax
result=object1Isobject2
TheIsoperatorsyntaxhastheseparts:
Part Descriptionresult Anynumericvariable.object1 Anyobjectname.object2 Anyobjectname.
Remarks
Ifobject1andobject2bothrefertothesameobject,resultisTrue;iftheydonot,resultisFalse.Twovariablescanbemadetorefertothesameobjectinseveralways.
Inthefollowingexample,AhasbeensettorefertothesameobjectasB:
SetA=BThefollowingexamplemakesAandBrefertothesameobjectasC:
SetA=C
SetB=C
Microsoft®VisualBasic®ScriptingEditionIsArrayFunction
LanguageReferenceVersion1
SeeAlso
Description
ReturnsaBooleanvalueindicatingwhetheravariableisanarray.
Syntax
IsArray(varname)
Thevarnameargumentcanbeanyvariable.
Remarks
IsArrayreturnsTrueifthevariableisanarray;otherwise,itreturnsFalse.IsArrayisespeciallyusefulwithvariantscontainingarrays.
ThefollowingexampleusestheIsArrayfunctiontotestwhetherMyVariableisanarray:
DimMyVariableDimMyArray(3)MyArray(0)="Sunday"MyArray(1)="Monday"MyArray(2)="Tuesday"MyVariable=IsArray(MyArray)'MyVariablecontains"True".
Microsoft®VisualBasic®ScriptingEditionIsDateFunction
LanguageReferenceVersion1
SeeAlso
Description
ReturnsaBooleanvalueindicatingwhetheranexpressioncanbeconvertedtoadate.
Syntax
IsDate(expression)
Theexpressionargumentcanbeanydateexpressionorstringexpressionrecognizableasadateortime.
Remarks
IsDatereturnsTrueiftheexpressionisadateorcanbeconvertedtoavaliddate;otherwise,itreturnsFalse.InMicrosoftWindows,therangeofvaliddatesisJanuary1,100A.D.throughDecember31,9999A.D.;therangesvaryamongoperatingsystems.
ThefollowingexampleusestheIsDatefunctiontodeterminewhetheranexpressioncanbeconvertedtoadate:
DimMyDate,YourDate,NoDate,MyCheckMyDate="October19,1962":YourDate=#10/19/62#:NoDate="Hello"MyCheck=IsDate(MyDate)'ReturnsTrue.MyCheck=IsDate(YourDate)'ReturnsTrue.MyCheck=IsDate(NoDate)'ReturnsFalse.
Microsoft®VisualBasic®ScriptingEdition
IsEmptyFunctionLanguageReference
Version1
SeeAlso
Description
ReturnsaBooleanvalueindicatingwhetheravariablehasbeeninitialized.
Syntax
IsEmpty(expression)
Theexpressionargumentcanbeanyexpression.However,becauseIsEmptyisusedtodetermineifindividualvariablesareinitialized,theexpressionargumentismostoftenasinglevariablename.
Remarks
IsEmptyreturnsTrueifthevariableisuninitialized,orisexplicitlysettoEmpty;otherwise,itreturnsFalse.Falseisalwaysreturnedifexpressioncontainsmorethanonevariable.
ThefollowingexampleusestheIsEmptyfunctiontodeterminewhetheravariablehasbeeninitialized:
DimMyVar,MyCheckMyCheck=IsEmpty(MyVar)'ReturnsTrue.MyVar=Null'AssignNull.MyCheck=IsEmpty(MyVar)'ReturnsFalse.MyVar=Empty'AssignEmpty.
MyCheck=IsEmpty(MyVar)'ReturnsTrue.
Microsoft®VisualBasic®ScriptingEditionIsNullFunction
LanguageReferenceVersion1
SeeAlso
Description
ReturnsaBooleanvaluethatindicateswhetheranexpressioncontainsnovaliddata(Null).
Syntax
IsNull(expression)
Theexpressionargumentcanbeanyexpression.
Remarks
IsNullreturnsTrueifexpressionisNull,thatis,itcontainsnovaliddata;otherwise,IsNullreturnsFalse.Ifexpressionconsistsofmorethanonevariable,NullinanyconstituentvariablecausesTruetobereturnedfortheentireexpression.
TheNullvalueindicatesthatthevariablecontainsnovaliddata.NullisnotthesameasEmpty,whichindicatesthatavariablehasnotyetbeeninitialized.Itisalsonotthesameasazero-lengthstring(""),whichissometimesreferredtoasanullstring.
ImportantUsetheIsNullfunctiontodeterminewhetheranexpressioncontainsaNullvalue.ExpressionsthatyoumightexpecttoevaluatetoTrueundersomecircumstances,suchasIfVar=NullandIfVar<>Null,arealwaysFalse.ThisisbecauseanyexpressioncontainingaNullisitselfNull,andtherefore,False.
ThefollowingexampleusestheIsNullfunctiontodeterminewhetheravariablecontainsaNull:
DimMyVar,MyCheckMyCheck=IsNull(MyVar)'ReturnsFalse.MyVar=Null'AssignNull.MyCheck=IsNull(MyVar)'ReturnsTrue.MyVar=Empty'AssignEmpty.MyCheck=IsNull(MyVar)'ReturnsFalse.
Microsoft®VisualBasic®ScriptingEdition
IsNumericFunction
LanguageReferenceVersion1
SeeAlso
Description
ReturnsaBooleanvalueindicatingwhetheranexpressioncanbeevaluatedasanumber.
Syntax
IsNumeric(expression)
Theexpressionargumentcanbeanyexpression.
Remarks
IsNumericreturnsTrueiftheentireexpressionisrecognizedasanumber;otherwise,itreturnsFalse.IsNumericreturnsFalseifexpressionisadateexpression.
ThefollowingexampleusestheIsNumericfunctiontodeterminewhetheravariablecanbeevaluatedasanumber:
DimMyVar,MyCheckMyVar=53'Assignavalue.MyCheck=IsNumeric(MyVar)'ReturnsTrue.MyVar="459.95"'Assignavalue.MyCheck=IsNumeric(MyVar)'ReturnsTrue.MyVar="45Help"'Assignavalue.MyCheck=IsNumeric(MyVar)'ReturnsFalse.
Microsoft®VisualBasic®ScriptingEdition
IsObjectFunctionLanguageReference
Version1
SeeAlso
Description
ReturnsaBooleanvalueindicatingwhetheranexpressionreferencesavalidAutomationobject.
Syntax
IsObject(expression)
Theexpressionargumentcanbeanyexpression.
Remarks
IsObjectreturnsTrueifexpressionisavariableofObjectsubtypeorauser-definedobject;otherwise,itreturnsFalse.
ThefollowingexampleusestheIsObjectfunctiontodetermineifanidentifierrepresentsanobjectvariable:
DimMyInt,MyCheck,MyObjectSetMyObject=MeMyCheck=IsObject(MyObject)'ReturnsTrue.MyCheck=IsObject(MyInt)'ReturnsFalse.
Microsoft®VisualBasic®ScriptingEditionJoinFunction
LanguageReferenceVersion2
SeeAlso
Description
Returnsastringcreatedbyjoininganumberofsubstringscontainedinanarray.
Syntax
Join(list[,delimiter])
TheJoinfunctionsyntaxhastheseparts:
Part Description
list Required.One-dimensionalarraycontainingsubstringstobejoined.
delimiter
Optional.Stringcharacterusedtoseparatethesubstringsinthereturnedstring.Ifomitted,thespacecharacter("")isused.Ifdelimiterisazero-lengthstring,allitemsinthelistareconcatenatedwithnodelimiters.
Remarks
ThefollowingexampleusestheJoinfunctiontojointhesubstringsofMyArray:
DimMyStringDimMyArray(4)MyArray(0)="Mr."
MyArray(1)="John"MyArray(2)="Doe"MyArray(3)="III"MyString=Join(MyArray)'MyStringcontains"Mr.JohnDoeIII".
Microsoft®VisualBasic®ScriptingEditionLBoundFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsthesmallestavailablesubscriptfortheindicateddimensionofanarray.
Syntax
LBound(arrayname[,dimension])
TheLBoundfunctionsyntaxhastheseparts:
Part Description
arrayname Nameofthearrayvariable;followsstandardvariablenamingconventions.
dimension
Wholenumberindicatingwhichdimension'slowerboundisreturned.Use1forthefirstdimension,2forthesecond,andsoon.Ifdimensionisomitted,1isassumed.
Remarks
TheLBoundfunctionisusedwiththeUBoundfunctiontodeterminethesizeofanarray.UsetheUBoundfunctiontofindtheupperlimitofanarraydimension.
Thelowerboundforanydimensionisalways0.
Microsoft®VisualBasic®ScriptingEditionLCaseFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsastringthathasbeenconvertedtolowercase.
Syntax
LCase(string)
Thestringargumentisanyvalidstringexpression.IfstringcontainsNull,Nullisreturned.
Remarks
Onlyuppercaselettersareconvertedtolowercase;alllowercaselettersandnonlettercharactersremainunchanged.
ThefollowingexampleusestheLCasefunctiontoconvertuppercaseletterstolowercase:
DimMyStringDimLCaseStringMyString="VBSCript"LCaseString=LCase(MyString)'LCaseStringcontains"vbscript".
Microsoft®VisualBasic®ScriptingEditionLeftFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsaspecifiednumberofcharactersfromtheleftsideofastring.
Syntax
Left(string,length)
TheLeftfunctionsyntaxhasthesearguments:
Part Description
string Stringexpressionfromwhichtheleftmostcharactersarereturned.IfstringcontainsNull,Nullisreturned.
length
Numericexpressionindicatinghowmanycharacterstoreturn.If0,azero-lengthstring("")isreturned.Ifgreaterthanorequaltothenumberofcharactersinstring,theentirestringisreturned.
Remarks
Todeterminethenumberofcharactersinstring,usetheLenfunction.
ThefollowingexampleusestheLeftfunctiontoreturnthefirstthreecharactersofMyString:
DimMyString,LeftStringMyString="VBSCript"LeftString=Left(MyString,3)'LeftStringcontains"VBS".
NoteTheLeftBfunctionisusedwithbytedatacontainedinastring.Insteadofspecifyingthenumberofcharacterstoreturn,lengthspecifiesthenumberofbytes.
Microsoft®VisualBasic®ScriptingEditionLenFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsthenumberofcharactersinastringorthenumberofbytesrequiredtostoreavariable.
Syntax
Len(string|varname)
TheLenfunctionsyntaxhastheseparts:
Part Description
string Anyvalidstringexpression.IfstringcontainsNull,Nullisreturned.
varname Anyvalidvariablename.IfvarnamecontainsNull,Nullisreturned.
Remarks
ThefollowingexampleusestheLenfunctiontoreturnthenumberofcharactersinastring:
DimMyStringMyString=Len("VBSCRIPT")'MyStringcontains8.
NoteTheLenBfunctionisusedwithbytedatacontainedinastring.Insteadofreturningthenumberofcharactersinastring,LenBreturnsthenumberofbytesusedtorepresentthatstring.
Microsoft®VisualBasic®ScriptingEdition
LengthPropertyLanguageReference
Version5
SeeAlsoAppliesTo
Description
Returnsthelengthofamatchfoundinasearchstring.
Syntax
object.Length
TheobjectargumentisalwaysaMatchobject.
Remarks
ThefollowingcodeillustratestheuseoftheLengthproperty:
FunctionRegExpTest(patrn,strng)DimregEx,Match,Matches 'Createvariable.SetregEx=NewRegExp 'Createregularexpression.regEx.Pattern=patrn 'Setpattern.regEx.IgnoreCase=True 'Setcaseinsensitivity.regEx.Global=True 'Setglobalapplicability.SetMatches=regEx.Execute(strng) 'Executesearch.ForEachMatchinMatches 'IterateMatchescollection.RetStr=RetStr&"Match"&I&"foundatposition"RetStr=RetStr&Match.FirstIndex&".MatchLengthis"RetStr=RetStr&Match.LengthRetStr=RetStr&"characters."&vbCRLF
NextRegExpTest=RetStrEndFunction
MsgBox(RegExpTest("is.","IS1is2IS3is4"))
Microsoft®VisualBasic®ScriptingEdition
LoadPictureFunction
LanguageReferenceVersion2
Description
Returnsapictureobject.Availableonlyon32-bitplatforms.
Syntax
LoadPicture(picturename)
Thepicturenameargumentisastringexpressionthatindicatesthenameofthepicturefiletobeloaded.
Remarks
GraphicsformatsrecognizedbyLoadPictureincludebitmap(.bmp)files,icon(.ico)files,run-lengthencoded(.rle)files,metafile(.wmf)files,enhancedmetafiles(.emf),GIF(.gif)files,andJPEG(.jpg)files.
Microsoft®VisualBasic®ScriptingEditionLogFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsthenaturallogarithmofanumber.
Syntax
Log(number)
Thenumberargumentcanbeanyvalidnumericexpressiongreaterthan0.
Remarks
Thenaturallogarithmisthelogarithmtothebasee.Theconstanteisapproximately2.718282.
Youcancalculatebase-nlogarithmsforanynumberxbydividingthenaturallogarithmofxbythenaturallogarithmofnasfollows:
Logn(x)=Log(x)/Log(n)ThefollowingexampleillustratesacustomFunctionthatcalculatesbase-10logarithms:
FunctionLog10(X)Log10=Log(X)/Log(10)EndFunction
Microsoft®VisualBasic®ScriptingEditionLTrim,RTrim,andTrimFunctions
LanguageReferenceVersion1
SeeAlso
Description
Returnsacopyofastringwithoutleadingspaces(LTrim),trailingspaces(RTrim),orbothleadingandtrailingspaces(Trim).
Syntax
LTrim(string)
RTrim(string)
Trim(string)
Thestringargumentisanyvalidstringexpression.IfstringcontainsNull,Nullisreturned.
Remarks
ThefollowingexampleusestheLTrim,RTrim,andTrimfunctionstotrimleadingspaces,trailingspaces,andbothleadingandtrailingspaces,respectively:
DimMyVarMyVar=LTrim("vbscript")'MyVarcontains"vbscript".
MyVar=RTrim("vbscript")'MyVarcontains"vbscript".MyVar=Trim("vbscript")'MyVarcontains"vbscript".
Microsoft®VisualBasic®ScriptingEditionMatchObject
LanguageReferenceVersion5
SeeAlsoProperties
Description
Providesaccesstotheread-onlypropertiesofaregularexpressionmatch.
Remarks
AMatchobjectcanbeonlycreatedusingtheExecutemethodoftheRegExpobject,whichactuallyreturnsacollectionofMatchobjects.AllMatchobjectpropertiesareread-only.
Whenaregularexpressionisexecuted,zeroormoreMatchobjectscanresult.EachMatchobjectprovidesaccesstothestringfoundbytheregularexpression,thelengthofthestring,andanindextowherethematchwasfound.
ThefollowingcodeillustratestheuseoftheMatchobject:
FunctionRegExpTest(patrn,strng)DimregEx,Match,Matches 'Createvariable.SetregEx=NewRegExp 'Createregularexpression.regEx.Pattern=patrn 'Setpattern.regEx.IgnoreCase=True 'Setcaseinsensitivity.regEx.Global=True 'Setglobalapplicability.SetMatches=regEx.Execute(strng) 'Executesearch.ForEachMatchinMatches 'IterateMatchescollection.
RetStr=RetStr&"Match"&I&"foundatposition"RetStr=RetStr&Match.FirstIndex&".MatchValueis"'RetStr=RetStr&Match.Value&"'."&vbCRLFNextRegExpTest=RetStrEndFunction
MsgBox(RegExpTest("is.","IS1is2IS3is4"))
Microsoft®VisualBasic®ScriptingEditionMatchesCollection
LanguageReferenceVersion5
SeeAlsoProperties
Description
CollectionofregularexpressionMatchobjects.
Remarks
AMatchescollectioncontainsindividualMatchobjects,andcanbeonlycreatedusingtheExecutemethodoftheRegExpobject.TheMatchescollection'sonepropertyisread-only,asaretheindividualMatchobjectproperties.
Whenaregularexpressionisexecuted,zeroormoreMatchobjectscanresult.EachMatchobjectprovidesaccesstothestringfoundbytheregularexpression,thelengthofthestring,andanindextowherethematchwasfound.
ThefollowingcodeillustrateshowtoobtainaMatchescollectionfromaregularexpressionsearchandhowtoiteratethecollection:
FunctionRegExpTest(patrn,strng)DimregEx,Match,Matches 'Createvariable.SetregEx=NewRegExp 'Createregularexpression.regEx.Pattern=patrn 'Setpattern.regEx.IgnoreCase=True 'Setcaseinsensitivity.regEx.Global=True 'Setglobalapplicability.
SetMatches=regEx.Execute(strng) 'Executesearch.ForEachMatchinMatches 'IterateMatchescollection.RetStr=RetStr&"Matchfoundatposition"RetStr=RetStr&Match.FirstIndex&".MatchValueis'"RetStr=RetStr&Match.Value&"'."&vbCRLFNextRegExpTest=RetStrEndFunction
MsgBox(RegExpTest("is.","IS1is2IS3is4"))
Microsoft®VisualBasic®ScriptingEditionMidFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsaspecifiednumberofcharactersfromastring.
Syntax
Mid(string,start[,length])
TheMidfunctionsyntaxhasthesearguments:
Part Description
string Stringexpressionfromwhichcharactersarereturned.IfstringcontainsNull,Nullisreturned.
startCharacterpositioninstringatwhichtheparttobetakenbegins.Ifstartisgreaterthanthenumberofcharactersinstring,Midreturnsazero-lengthstring("").
length
Numberofcharacterstoreturn.Ifomittedoriftherearefewerthanlengthcharactersinthetext(includingthecharacteratstart),allcharactersfromthestartpositiontotheendofthestringarereturned.
Remarks
Todeterminethenumberofcharactersinstring,usetheLenfunction.
ThefollowingexampleusestheMidfunctiontoreturnsixcharacters,beginningwiththefourthcharacter,inastring:
DimMyVar
MyVar=Mid("VBScriptisfun!",4,6)'MyVarcontains"Script".
NoteTheMidBfunctionisusedwithbytedatacontainedinastring.Insteadofspecifyingthenumberofcharacters,theargumentsspecifynumbersofbytes.
Microsoft®VisualBasic®ScriptingEditionMinuteFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsawholenumberbetween0and59,inclusive,representingtheminuteofthehour.
Syntax
Minute(time)
Thetimeargumentisanyexpressionthatcanrepresentatime.IftimecontainsNull,Nullisreturned.
Remarks
ThefollowingexampleusestheMinutefunctiontoreturntheminuteofthehour:
DimMyVarMyVar=Minute(Now)
Microsoft®VisualBasic®ScriptingEdition
MiscellaneousConstants
LanguageReferenceVersion2
SeeAlso
SincethisconstantisbuiltintoVBScript,youdon'thavetodefineitbeforeusingit.Useitanywhereinyourcodetorepresentthevaluesshown.
Constant Value Description
vbObjectError -2147221504
User-definederrornumbersshouldbegreaterthanthisvalue,forexample,
Err.RaiseNumber=vbObjectError+1000
Microsoft®VisualBasic®ScriptingEditionModOperator
LanguageReferenceVersion1
SeeAlso
Description
Dividestwonumbersandreturnsonlytheremainder.
Syntax
result=number1Modnumber2
TheModoperatorsyntaxhastheseparts:
Part Descriptionresult Anynumericvariable.number1 Anynumericexpression.number2 Anynumericexpression.
Remarks
Themodulus,orremainder,operatordividesnumber1bynumber2(roundingfloating-pointnumberstointegers)andreturnsonlytheremainderasresult.Forexample,inthefollowingexpression,A(whichisresult)equals5.
A=19Mod6.7IfanyexpressionisNull,resultisalsoNull.AnyexpressionthatisEmptyistreatedas0.
Microsoft®VisualBasic®ScriptingEditionMonthFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsawholenumberbetween1and12,inclusive,representingthemonthoftheyear.
Syntax
Month(date)
Thedateargumentisanyexpressionthatcanrepresentadate.IfdatecontainsNull,Nullisreturned.
Remarks
ThefollowingexampleusestheMonthfunctiontoreturnthecurrentmonth:
DimMyVarMyVar=Month(Now)'MyVarcontainsthenumbercorrespondingto'thecurrentmonth.
Microsoft®VisualBasic®ScriptingEdition
MonthNameFunction
LanguageReferenceVersion2
SeeAlso
Description
Returnsastringindicatingthespecifiedmonth.
Syntax
MonthName(month[,abbreviate])
TheMonthNamefunctionsyntaxhastheseparts:
Part Description
month Required.Thenumericdesignationofthemonth.Forexample,Januaryis1,Februaryis2,andsoon.
abbreviate
Optional.Booleanvaluethatindicatesifthemonthnameistobeabbreviated.Ifomitted,thedefaultisFalse,whichmeansthatthemonthnameisnotabbreviated.
Remarks
ThefollowingexampleusestheMonthNamefunctiontoreturnanabbreviatedmonthnameforadateexpression:
DimMyVarMyVar=MonthName(10,True)'MyVarcontains"Oct".
Microsoft®VisualBasic®ScriptingEditionMsgBoxConstants
LanguageReferenceVersion2
SeeAlso
ThefollowingconstantsareusedwiththeMsgBoxfunctiontoidentifywhatbuttonsandiconsappearonamessageboxandwhichbuttonisthedefault.Inaddition,themodalityoftheMsgBoxcanbespecified.SincetheseconstantsarebuiltintoVBScript,youdon'thavetodefinethembeforeusingthem.Usethemanywhereinyourcodetorepresentthevaluesshownforeach.
Constant Value DescriptionvbOKOnly 0 DisplayOKbuttononly.vbOKCancel 1 DisplayOKandCancelbuttons.
vbAbortRetryIgnore 2 DisplayAbort,Retry,andIgnorebuttons.
vbYesNoCancel 3 DisplayYes,No,andCancelbuttons.
vbYesNo 4 DisplayYesandNobuttons.
vbRetryCancel 5 DisplayRetryandCancelbuttons.
vbCritical 16 DisplayCriticalMessageicon.vbQuestion 32 DisplayWarningQueryicon.vbExclamation 48 DisplayWarningMessageicon.
vbInformation 64 DisplayInformationMessageicon.
vbDefaultButton1 0 Firstbuttonisthedefault.vbDefaultButton2 256 Secondbuttonisthedefault.vbDefaultButton3 512 Thirdbuttonisthedefault.vbDefaultButton4 768 Fourthbuttonisthedefault.
vbApplicationModal 0Applicationmodal.Theusermustrespondtothemessageboxbeforecontinuingworkinthecurrentapplication.
vbSystemModal 4096
Systemmodal.OnWin16systems,allapplicationsaresuspendeduntiltheuserrespondstothemessagebox.OnWin32systems,thisconstantprovidesanapplicationmodalmessageboxthatalwaysremainsontopofanyotherprogramsyoumayhaverunning.
ThefollowingconstantsareusedwiththeMsgBoxfunctiontoidentifywhichbuttonauserhasselected.Theseconstantsareonlyavailablewhenyourprojecthasanexplicitreferencetotheappropriatetypelibrarycontainingtheseconstantdefinitions.ForVBScript,youmustexplicitlydeclaretheseconstantsinyourcode.
Constant Value DescriptionvbOK 1 OKbuttonwasclicked.vbCancel 2 Cancelbuttonwasclicked.vbAbort 3 Abortbuttonwasclicked.vbRetry 4 Retrybuttonwasclicked.vbIgnore 5 Ignorebuttonwasclicked.vbYes 6 Yesbuttonwasclicked.vbNo 7 Nobuttonwasclicked.
Microsoft®VisualBasic®ScriptingEditionMsgBoxFunction
LanguageReferenceVersion1
SeeAlso
Description
Displaysamessageinadialogbox,waitsfortheusertoclickabutton,andreturnsavalueindicatingwhichbuttontheuserclicked.
Syntax
MsgBox(prompt[,buttons][,title][,helpfile,context])
TheMsgBoxfunctionsyntaxhasthesearguments:
Part Description
prompt
Stringexpressiondisplayedasthemessageinthedialogbox.Themaximumlengthofpromptisapproximately1024characters,dependingonthewidthofthecharactersused.Ifpromptconsistsofmorethanoneline,youcanseparatethelinesusingacarriagereturncharacter(Chr(13)),alinefeedcharacter(Chr(10)),orcarriagereturn–linefeedcharactercombination(Chr(13)&Chr(10))betweeneachline.
buttons
Numericexpressionthatisthesumofvaluesspecifyingthenumberandtypeofbuttonstodisplay,theiconstyletouse,theidentityofthedefaultbutton,andthemodalityofthemessagebox.SeeSettingssectionforvalues.Ifomitted,thedefaultvalueforbuttonsis0.
titleStringexpressiondisplayedinthetitlebarofthedialogbox.Ifyouomittitle,theapplicationnameisplacedinthetitlebar.StringexpressionthatidentifiestheHelpfiletouseto
helpfile providecontext-sensitiveHelpforthedialogbox.Ifhelpfileisprovided,contextmustalsobeprovided.Notavailableon16-bitplatforms.
context
NumericexpressionthatidentifiestheHelpcontextnumberassignedbytheHelpauthortotheappropriateHelptopic.Ifcontextisprovided,helpfilemustalsobeprovided.Notavailableon16-bitplatforms.
Settings
Thebuttonsargumentsettingsare:
Constant Value DescriptionvbOKOnly 0 DisplayOKbuttononly.vbOKCancel 1 DisplayOKandCancelbuttons.
vbAbortRetryIgnore 2 DisplayAbort,Retry,andIgnorebuttons.
vbYesNoCancel 3 DisplayYes,No,andCancelbuttons.
vbYesNo 4 DisplayYesandNobuttons.
vbRetryCancel 5 DisplayRetryandCancelbuttons.
vbCritical 16 DisplayCriticalMessageicon.vbQuestion 32 DisplayWarningQueryicon.vbExclamation 48 DisplayWarningMessageicon.
vbInformation 64 DisplayInformationMessageicon.
vbDefaultButton1 0 Firstbuttonisdefault.vbDefaultButton2 256 Secondbuttonisdefault.vbDefaultButton3 512 Thirdbuttonisdefault.vbDefaultButton4 768 Fourthbuttonisdefault.
Applicationmodal;theusermustrespondtothemessageboxbefore
vbApplicationModal 0 continuingworkinthecurrentapplication.
vbSystemModal 4096Systemmodal;allapplicationsaresuspendeduntiltheuserrespondstothemessagebox.
Thefirstgroupofvalues(0–5)describesthenumberandtypeofbuttonsdisplayedinthedialogbox;thesecondgroup(16,32,48,64)describestheiconstyle;thethirdgroup(0,256,512,768)determineswhichbuttonisthedefault;andthefourthgroup(0,4096)determinesthemodalityofthemessagebox.Whenaddingnumberstocreateafinalvaluefortheargumentbuttons,useonlyonenumberfromeachgroup.
ReturnValues
TheMsgBoxfunctionhasthefollowingreturnvalues:
Constant Value ButtonvbOK 1 OKvbCancel 2 CancelvbAbort 3 AbortvbRetry 4 RetryvbIgnore 5 IgnorevbYes 6 YesvbNo 7 No
Remarks
Whenbothhelpfileandcontextareprovided,theusercanpressF1toviewtheHelptopiccorrespondingtothecontext.
IfthedialogboxdisplaysaCancelbutton,pressingtheESCkeyhasthesameeffectasclickingCancel.IfthedialogboxcontainsaHelpbutton,context-sensitiveHelpisprovidedforthedialogbox.However,novalueisreturneduntiloneoftheotherbuttonsisclicked.
WhentheMsgBoxfunctionisusedwithMicrosoftInternetExplorer,thetitleofanydialogpresentedalwayscontains"VBScript:"todifferentiateitfromstandardsystemdialogs.
ThefollowingexampleusestheMsgBoxfunctiontodisplayamessageboxandreturnavaluedescribingwhichbuttonwasclicked:
DimMyVarMyVar=MsgBox("HelloWorld!",65,"MsgBoxExample")'MyVarcontainseither1or2,'dependingonwhichbuttonis'clicked.
Microsoft®VisualBasic®ScriptingEdition*Operator
LanguageReferenceVersion1
SeeAlso
Description
Multipliestwonumbers.
Syntax
result=number1*number2
The*operatorsyntaxhastheseparts:
Part Descriptionresult Anynumericvariable.number1 Anynumericexpression.number2 Anynumericexpression.
Remarks
IfoneorbothexpressionsareNullexpressions,resultisNull.IfanexpressionisEmpty,itistreatedasifitwere0.
Microsoft®VisualBasic®ScriptingEdition-Operator
LanguageReferenceVersion1
SeeAlso
Description
Findsthedifferencebetweentwonumbersorindicatesthenegativevalueofanumericexpression.
Syntax1
result=number1-number2
Syntax2
-number
The-operatorsyntaxhastheseparts:
Part Descriptionresult Anynumericvariable.number Anynumericexpression.number1 Anynumericexpression.number2 Anynumericexpression.
Remarks
InSyntax1,the-operatoristhearithmeticsubtractionoperatorusedtofindthedifferencebetweentwonumbers.InSyntax2,the-operatorisusedastheunarynegationoperatortoindicatethenegativevalueofanexpression.
IfoneorbothexpressionsareNullexpressions,resultisNull.IfanexpressionisEmpty,itistreatedasifitwere0.
Microsoft®VisualBasic®ScriptingEditionNotOperator
LanguageReferenceVersion1
SeeAlso
Description
Performslogicalnegationonanexpression.
Syntax
result=Notexpression
TheNotoperatorsyntaxhastheseparts:
Part Descriptionresult Anynumericvariable.expression Anyexpression.
Remarks
Thefollowingtableillustrateshowresultisdetermined:
Ifexpressionis ThenresultisTrue FalseFalse TrueNull Null
Inaddition,theNotoperatorinvertsthebitvaluesofanyvariableandsetsthecorrespondingbitinresultaccordingtothefollowingtable:
Bitinexpression Bitinresult0 11 0
Microsoft®VisualBasic®ScriptingEditionNowFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsthecurrentdateandtimeaccordingtothesettingofyourcomputer'ssystemdateandtime.
Syntax
Now
Remarks
ThefollowingexampleusestheNowfunctiontoreturnthecurrentdateandtime:
DimMyVarMyVar=Now'MyVarcontainsthecurrentdateandtime.
Microsoft®VisualBasic®ScriptingEditionNothingLanguageReference
Version1
SeeAlso
Description
TheNothingkeywordinVBScriptisusedtodisassociateanobjectvariablefromanyactualobject.UsetheSetstatementtoassignNothingtoanobjectvariable.Forexample:
SetMyObject=NothingSeveralobjectvariablescanrefertothesameactualobject.WhenNothingisassignedtoanobjectvariable,thatvariablenolongerreferstoanyactualobject.Whenseveralobjectvariablesrefertothesameobject,memoryandsystemresourcesassociatedwiththeobjecttowhichthevariablesreferarereleasedonlyafterallofthemhavebeensettoNothing,eitherexplicitlyusingSet,orimplicitlyafterthelastobjectvariablesettoNothinggoesoutofscope.
Microsoft®VisualBasic®ScriptingEditionNullLanguageReference
Version1
SeeAlso
Description
TheNullkeywordisusedtoindicatethatavariablecontainsnovaliddata.ThisisnotthesamethingasEmpty.
Microsoft®VisualBasic®ScriptingEditionNumberProperty
LanguageReferenceVersion1
SeeAlsoAppliesto
Description
Returnsorsetsanumericvaluespecifyinganerror.NumberistheErrobject'sdefaultproperty.
Syntax
object.Number[=errornumber]
TheNumberpropertysyntaxhastheseparts:
Part Descriptionobject AlwaystheErrobject.
errornumber AnintegerrepresentingaVBScripterrornumberoranSCODEerrorvalue.
Remarks
Whenreturningauser-definederrorfromanAutomationobject,setErr.NumberbyaddingthenumberyouselectedasanerrorcodetotheconstantvbObjectError.
ThefollowingcodeillustratestheuseoftheNumberproperty
OnErrorResumeNextErr.RaisevbObjectError+1,"SomeObject" 'RaiseObjectError#1.MsgBox("Error#"&CStr(Err.Number)&""&Err.Description)Err.Clear 'Cleartheerror.
Microsoft®VisualBasic®ScriptingEditionOctFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsastringrepresentingtheoctalvalueofanumber.
Syntax
Oct(number)
Thenumberargumentisanyvalidexpression.
Remarks
Ifnumberisnotalreadyawholenumber,itisroundedtothenearestwholenumberbeforebeingevaluated.
Ifnumberis OctreturnsNull Null.Empty Zero(0).Anyothernumber Upto11octalcharacters,
Youcanrepresentoctalnumbersdirectlybyprecedingnumbersintheproperrangewith&O.Forexample,&O10istheoctalnotationfordecimal8.
ThefollowingexampleusestheOctfunctiontoreturntheoctalvalueofanumber:
DimMyOctMyOct=Oct(4)'Returns4.MyOct=Oct(8)'Returns10.MyOct=Oct(459)'Returns713.
Microsoft®VisualBasic®ScriptingEditionOnErrorStatement
LanguageReferenceVersion1
SeeAlso
Description
Enablesordisableserror-handling.
Syntax
OnErrorResumeNextOnErrorGoTo0
Remarks
Ifyoudon'tuseanOnErrorResumeNextstatementanywhereinyourcode,anyrun-timeerrorthatoccurscancauseanerrormessagetobedisplayedandcodeexecutionstopped.However,theexactbehaviorisdeterminedbythehostrunningthecode.Thehostcansometimesopttohandlesucherrorsdifferently.Insomecases,thescriptdebuggermaybeinvokedatthepointoftheerror.Instillothercases,theremaybenoapparentindicationthatanyerroroccurredbecausethehostdoesnottonotifytheuser.Again,thisispurelyafunctionofhowthehosthandlesanyerrorsthatoccur.
Withinanyparticularprocedure,anerrorisnotnecessarilyfatalaslongaserror-handlingisenabledsomewherealongthecallstack.Iflocalerror-handlingisnotenabledinaprocedureandanerroroccurs,controlispassedbackthroughthecallstackuntilaprocedurewitherror-handlingenabledisfoundandtheerrorishandledatthatpoint.Ifnoprocedureinthecallstackisfoundtohaveerror-handlingenabled,anerrormessageisdisplayedatthatpointandexecutionstopsorthehosthandlestheerrorasappropriate.
OnErrorResumeNextcausesexecutiontocontinuewiththestatementimmediatelyfollowingthestatementthatcausedtherun-timeerror,orwiththestatementimmediatelyfollowingthemostrecentcalloutoftheprocedurecontainingtheOnErrorResumeNextstatement.Thisallowsexecutiontocontinuedespitearun-timeerror.Youcanthenbuildtheerror-handlingroutineinlinewithintheprocedure.
AnOnErrorResumeNextstatementbecomesinactivewhenanotherprocedureiscalled,soyoushouldexecuteanOnErrorResumeNextstatementineachcalledroutineifyouwantinlineerrorhandlingwithinthatroutine.Whenaprocedureisexited,theerror-handlingcapabilityrevertstowhatevererror-handlingwasinplacebeforeenteringtheexitedprocedure.
UseOnErrorGoTo0todisableerrorhandlingifyouhavepreviouslyenableditusingOnErrorResumeNext.
ThefollowingexampleillustratesuseoftheOnErrorResumeNextstatement:
OnErrorResumeNextErr.Raise6'Raiseanoverflowerror.MsgBox"Error#"&CStr(Err.Number)&""&Err.DescriptionErr.Clear'Cleartheerror.
Microsoft®VisualBasic®ScriptingEdition
OperatorPrecedence
LanguageReferenceVersion1
SeeAlso
Description
Whenseveraloperationsoccurinanexpression,eachpartisevaluatedandresolvedinapredeterminedordercalledoperatorprecedence.Parenthesescanbeusedtooverridetheorderofprecedenceandforcesomepartsofanexpressiontobeevaluatedbeforeotherparts.Operationswithinparenthesesarealwaysperformedbeforethoseoutside.Withinparentheses,however,normaloperatorprecedenceismaintained.
Whenexpressionscontainoperatorsfrommorethanonecategory,arithmeticoperatorsareevaluatedfirst,comparisonoperatorsareevaluatednext,andlogicaloperatorsareevaluatedlast.Comparisonoperatorsallhaveequalprecedence;thatis,theyareevaluatedintheleft-to-rightorderinwhichtheyappear.Arithmeticandlogicaloperatorsareevaluatedinthefollowingorderofprecedence:
Arithmetic Comparison LogicalExponentiation(^) Equality(=) NotNegation(-) Inequality(<>) AndMultiplicationanddivision(*,/) Lessthan(<) Or
Integerdivision(\) Greaterthan(>) XorModulusarithmetic(Mod) Lessthanorequalto(<=) EqvAdditionandsubtraction(+,-)
Greaterthanorequalto(>=) Imp
Stringconcatenation(&) Is &
Whenmultiplicationanddivisionoccurtogetherinanexpression,eachoperationisevaluatedasitoccursfromlefttoright.Likewise,whenadditionandsubtractionoccurtogetherinanexpression,eachoperationisevaluatedinorderofappearancefromlefttoright.
Thestringconcatenationoperator(&)isnotanarithmeticoperator,butinprecedenceitdoesfall
afterallarithmeticoperatorsandbeforeallcomparisonoperators.TheIsoperatorisanobjectreferencecomparisonoperator.Itdoesnotcompareobjectsortheirvalues;itchecksonlytodetermineiftwoobjectreferencesrefertothesameobject.
Microsoft®VisualBasic®ScriptingEditionOptionExplicitStatement
LanguageReferenceVersion1
Description
Forcesexplicitdeclarationofallvariablesinascript.
Syntax
OptionExplicit
Remarks
Ifused,theOptionExplicitstatementmustappearinascriptbeforeanyotherstatements.
WhenyouusetheOptionExplicitstatement,youmustexplicitlydeclareallvariablesusingtheDim,Private,Public,orReDimstatements.Ifyouattempttouseanundeclaredvariablename,anerroroccurs.
TipUseOptionExplicittoavoidincorrectlytypingthenameofanexistingvariableortoavoidconfusionincodewherethescopeofthevariableisnotclear.
ThefollowingexampleillustratesuseoftheOptionExplicitstatement:
OptionExplicit'Forceexplicitvariabledeclaration.DimMyVar'Declarevariable.
MyInt=10'Undeclaredvariablegenerateserror.MyVar=10'Declaredvariabledoesnotgenerateerror.
Microsoft®VisualBasic®ScriptingEditionOrOperator
LanguageReferenceVersion1
SeeAlso
Description
Performsalogicaldisjunctionontwoexpressions.
Syntax
result=expression1Orexpression2
TheOroperatorsyntaxhastheseparts:
Part Descriptionresult Anynumericvariable.expression1 Anyexpression.expression2 Anyexpression.
Remarks
IfeitherorbothexpressionsevaluatetoTrue,resultisTrue.Thefollowingtableillustrateshowresultisdetermined:
Ifexpression1is Andexpression2is ThenresultisTrue True TrueTrue False TrueTrue Null TrueFalse True TrueFalse False FalseFalse Null NullNull True True
Null False NullNull Null Null
TheOroperatoralsoperformsabitwisecomparisonofidenticallypositionedbitsintwonumericexpressionsandsetsthecorrespondingbitinresultaccordingtothefollowingtable:
Ifbitinexpression1is Andbitinexpression2is Thenresultis
0 0 00 1 11 0 11 1 1
Microsoft®VisualBasic®ScriptingEditionPatternProperty
LanguageReferenceVersion5
SeeAlsoAppliesto
Description
Setsorreturnstheregularexpressionpatternbeingsearchedfor.
Syntax
object.Pattern[="searchstring"]
ThePatternpropertysyntaxhastheseparts:
Part Descriptionobject Required.AlwaysaRegExpobjectvariable.
searchstring Optional.Regularstringexpressionbeingsearchedfor.MayincludeanyoftheregularexpressioncharactersdefinedinthetableintheSettingssection.
Settings
Specialcharactersandsequencesareusedinwritingpatternsforregularexpressions.Thefollowingtabledescribesandgivesanexampleofthecharactersandsequencesthatcanbeused.
Character Description
\Marksthenextcharacteraseitheraspecialcharacteroraliteral.Forexample,"n"matchesthecharacter"n"."\n"matchesanewlinecharacter.Thesequence"\\"matches"\"and"\("matches"(".
^ Matchesthebeginningofinput.
$ Matchestheendofinput.
* Matchestheprecedingcharacterzeroormoretimes.Forexample,"zo*"matcheseither"z"or"zoo".
+ Matchestheprecedingcharacteroneormoretimes.Forexample,"zo+"matches"zoo"butnot"z".
? Matchestheprecedingcharacterzerooronetime.Forexample,"a?ve?"matchesthe"ve"in"never".
. Matchesanysinglecharacterexceptanewlinecharacter.
(pattern)Matchespatternandremembersthematch.ThematchedsubstringcanberetrievedfromtheresultingMatchescollection,usingItem[0]...[n].Tomatchparenthesescharacters(),use"\("or"\)".
x|y Matcheseitherxory.Forexample,"z|food"matches"z"or"food"."(z|f)oo"matches"zoo"or"food".
{n} nisanonnegativeinteger.Matchesexactlyntimes.Forexample,"o{2}"doesnotmatchthe"o"in"Bob,"butmatchesthefirsttwoo'sin"foooood".
{n,}nisanonnegativeinteger.Matchesatleastntimes.Forexample,"o{2,}"doesnotmatchthe"o"in"Bob"andmatchesalltheo'sin"foooood.""o{1,}"isequivalentto"o+"."o{0,}"isequivalentto"o*".
{n,m}mandnarenonnegativeintegers.Matchesatleastnandatmostmtimes.Forexample,"o{1,3}"matchesthefirstthreeo'sin"fooooood.""o{0,1}"isequivalentto"o?".
[xyz] Acharacterset.Matchesanyoneoftheenclosedcharacters.Forexample,"[abc]"matchesthe"a"in"plain".
[^xyz] Anegativecharacterset.Matchesanycharacternotenclosed.Forexample,"[^abc]"matchesthe"p"in"plain".
[a-z] Arangeofcharacters.Matchesanycharacterinthespecifiedrange.Forexample,"[a-z]"matchesanylowercasealphabeticcharacterintherange"a"through"z".
[^m-z] Anegativerangecharacters.Matchesanycharacternotinthespecifiedrange.Forexample,"[m-z]"matchesanycharacternotintherange"m"through"z".
\b Matchesawordboundary,thatis,thepositionbetweenawordandaspace.Forexample,"er\b"matchesthe"er"in"never"butnotthe"er"in"verb".
\B Matchesanonwordboundary."ea*r\B"matchesthe"ear"in"neverearly".
\d Matchesadigitcharacter.Equivalentto[0-9].
\D Matchesanondigitcharacter.Equivalentto[^0-9].
\f Matchesaform-feedcharacter.
\n Matchesanewlinecharacter.
\r Matchesacarriagereturncharacter.
\s Matchesanywhitespaceincludingspace,tab,form-feed,etc.Equivalentto"[\f\n\r\t\v]".
\S Matchesanynonwhitespacecharacter.Equivalentto"[^\f\n\r\t\v]".
\t Matchesatabcharacter.
\v Matchesaverticaltabcharacter.
\w Matchesanywordcharacterincludingunderscore.Equivalentto"[A-Za-z0-9_]".
\W Matchesanynonwordcharacter.Equivalentto"[^A-Za-z0-9_]".
\num Matchesnum,wherenumisapositiveinteger.Areferencebacktorememberedmatches.Forexample,"(.)\1"matchestwoconsecutiveidenticalcharacters.
\n
Matchesn,wherenisanoctalescapevalue.Octalescapevaluesmustbe1,2,or3digitslong.Forexample,"\11"and"\011"bothmatchatabcharacter."\0011"istheequivalentof"\001"&"1".Octalescapevaluesmustnotexceed256.Iftheydo,onlythefirsttwodigitscomprisetheexpression.AllowsASCIIcodestobeusedinregularexpressions.
Matchesn,wherenisahexadecimalescapevalue.Hexadecimalescapevaluesmust
\xn beexactlytwodigitslong.Forexample,"\x41"matches"A"."\x041"isequivalentto"\x04"&"1".AllowsASCIIcodestobeusedinregularexpressions.
Remarks
ThefollowingcodeillustratestheuseofthePatternproperty:
FunctionRegExpTest(patrn,strng)DimregEx,Match,Matches 'Createvariable.SetregEx=NewRegExp 'Createaregularexpression.regEx.Pattern=patrn 'Setpattern.regEx.IgnoreCase=True 'Setcaseinsensitivity.regEx.Global=True 'Setglobalapplicability.SetMatches=regEx.Execute(strng) 'Executesearch.ForEachMatchinMatches 'IterateMatchescollection.RetStr=RetStr&"Matchfoundatposition"RetStr=RetStr&Match.FirstIndex&".MatchValueis'"RetStr=RetStr&Match.Value&"'."&vbCRLFNextRegExpTest=RetStrEndFunction
MsgBox(RegExpTest("is.","IS1is2IS3is4"))
Microsoft®VisualBasic®ScriptingEditionPrivateStatement
LanguageReferenceVersion2
SeeAlso
Description
Declaresprivatevariablesandallocatesstoragespace.Declares,inaClassblock,aprivatevariable.
Syntax
Privatevarname[([subscripts])][,varname[([subscripts])]]...
ThePrivatestatementsyntaxhastheseparts:
Part Descriptionvarname Nameofthevariable;followsstandardvariablenamingconventions.
subscripts
Dimensionsofanarrayvariable;upto60multipledimensionsmaybedeclared.Thesubscriptsargumentusesthefollowingsyntax:
upper[,upper]...
Thelowerboundofanarrayisalwayszero.
Remarks
Privatestatementvariablesareavailableonlytothescriptinwhichtheyaredeclared.
Avariablethatreferstoanobjectmustbeassignedanexisting
objectusingtheSetstatementbeforeitcanbeused.Untilitisassignedanobject,thedeclaredobjectvariableisinitializedasEmpty.
YoucanalsousethePrivatestatementwithemptyparenthesestodeclareadynamicarray.Afterdeclaringadynamicarray,usetheReDimstatementwithinaproceduretodefinethenumberofdimensionsandelementsinthearray.IfyoutrytoredeclareadimensionforanarrayvariablewhosesizewasexplicitlyspecifiedinaPrivate,Public,orDimstatement,anerroroccurs.
TipWhenyouusethePrivatestatementinaprocedure,yougenerallyputthePrivatestatementatthebeginningoftheprocedure.
ThefollowingexampleillustratesuseofthePrivatestatement:
PrivateMyNumber 'PrivateVariantvariable.PrivateMyArray(9)'Privatearrayvariable. 'MultiplePrivatedeclarationsofVariantvariables.PrivateMyNumber,MyVar,YourNumber
Microsoft®VisualBasic®ScriptingEdition
PropertyGetStatement
LanguageReferenceVersion5
SeeAlso
Description
Declares,inaClassblock,thename,arguments,andcodethatformthebodyofaPropertyprocedurethatgets(returns)thevalueofaproperty.
Syntax
[Public[Default]|Private]PropertyGetname[(arglist)][statements][[Set]name=expression][ExitProperty][statements][[Set]name=expression]EndProperty
ThePropertyGetstatementsyntaxhastheseparts:
Part Description
Public IndicatesthatthePropertyGetprocedureisaccessibletoallotherproceduresinallscripts.
Default UsedonlywiththePublickeywordtoindicatethatthepropertydefinedinthePropertyGetprocedureisthedefaultpropertyfortheclass.
Private IndicatesthatthePropertyGetprocedureisaccessibleonlytootherproceduresintheClassblockwhereit'sdeclared.
nameNameofthePropertyGetprocedure;followsstandardvariablenamingconventions,exceptthatthenamecanbethesameasaPropertyLetorPropertySetprocedureinthesameClassblock.ListofvariablesrepresentingargumentsthatarepassedtothePropertyGetprocedure
arglist whenitiscalled.Multipleargumentsareseparatedbycommas.ThenameofeachargumentinaPropertyGetproceduremustbethesameasthecorrespondingargumentinaPropertyLetprocedure(ifoneexists).
statements AnygroupofstatementstobeexecutedwithinthebodyofthePropertyGetprocedure.
Set KeywordusedwhenassigninganobjectasthereturnvalueofaPropertyGetprocedure.
expression ReturnvalueofthePropertyGetprocedure.
Remarks
IfnotexplicitlyspecifiedusingeitherPublicorPrivate,PropertyGetproceduresarepublicbydefault,thatis,theyarevisibletoallotherproceduresinyourscript.ThevalueoflocalvariablesinaPropertyGetprocedureisnotpreservedbetweencallstotheprocedure.
Youcan'tdefineaPropertyGetprocedureinsideanyotherprocedure(e.g.FunctionorPropertyLet).
TheExitPropertystatementcausesanimmediateexitfromaPropertyGetprocedure.ProgramexecutioncontinueswiththestatementthatfollowsthestatementthatcalledthePropertyGetprocedure.AnynumberofExitPropertystatementscanappearanywhereinaPropertyGetprocedure.
LikeaSubandPropertyLetprocedure,aPropertyGetprocedureisaseparateprocedurethatcantakearguments,performaseriesofstatements,andchangethevalueofitsarguments.However,unlikeaSubandPropertyLet,youcanuseaPropertyGetprocedureontherightsideofanexpressioninthesamewayyouuseaFunctionorpropertynamewhenyouwanttoreturnthevalueofaproperty.
Microsoft®VisualBasic®ScriptingEdition
PropertyLetStatement
LanguageReferenceVersion5
SeeAlso
Description
Declares,inaClassblock,thename,arguments,andcodethatformthebodyofaPropertyprocedurethatassigns(sets)thevalueofaproperty.
Syntax
[Public|Private]PropertyLetname([arglist,]value)[statements][ExitProperty][statements]EndProperty
ThePropertyLetstatementsyntaxhastheseparts:
Part Description
Public IndicatesthatthePropertyLetprocedureisaccessibletoallotherproceduresinallscripts.
Private IndicatesthatthePropertyLetprocedureisaccessibleonlytootherproceduresintheClassblockwhereit'sdeclared.
nameNameofthePropertyLetprocedure;followsstandardvariablenamingconventions,exceptthatthenamecanbethesameasaPropertyGetorPropertySetprocedureinthesameClassblock.
arglist
ListofvariablesrepresentingargumentsthatarepassedtothePropertyLetprocedurewhenitiscalled.Multipleargumentsareseparatedbycommas.ThenameofeachargumentinaPropertyLetproceduremustbethesameasthecorrespondingargumentinaPropertyGetprocedure.Inaddition,thePropertyLetprocedurewillalwayshaveonemoreargumentthanitscorrespondingPropertyGetprocedure.Thatargumentisthevaluebeingassignedtotheproperty.
value Variabletocontainthevaluetobeassignedtotheproperty.Whentheprocedureiscalled,thisargumentappearsontherightsideofthecallingexpression.
statements AnygroupofstatementstobeexecutedwithinthebodyofthePropertyLetprocedure.
NoteVersionVersionEveryPropertyLetstatementmustdefineatleastoneargumentfortheprocedureitdefines.Thatargument(orthelastargumentifthereismorethanone)containstheactualvaluetobeassignedtothepropertywhentheproceduredefinedbythePropertyLetstatementisinvoked.Thatargumentisreferredtoasvalueintheprecedingsyntax.
Remarks
IfnotexplicitlyspecifiedusingeitherPublicorPrivate,PropertyLetproceduresarepublicbydefault,thatis,theyarevisibletoallotherproceduresinyourscript.ThevalueoflocalvariablesinaPropertyLetprocedureisnotpreservedbetweencallstotheprocedure.
Youcan'tdefineaPropertyLetprocedureinsideanyotherprocedure(e.g.FunctionorPropertyGet).
TheExitPropertystatementcausesanimmediateexitfromaPropertyLetprocedure.ProgramexecutioncontinueswiththestatementthatfollowsthestatementthatcalledthePropertyLetprocedure.AnynumberofExitPropertystatementscanappearanywhereinaPropertyLetprocedure.
LikeaFunctionandPropertyGetprocedure,aPropertyLetprocedureisaseparateprocedurethatcantakearguments,performaseriesofstatements,andchangethevalueofitsarguments.However,unlikeaFunctionandPropertyGetprocedure,bothofwhichreturnavalue,youcanonlyuseaPropertyLetprocedureontheleftsideofapropertyassignmentexpression.
Microsoft®VisualBasic®ScriptingEdition
PropertySetStatement
LanguageReferenceVersion5
SeeAlso
Description
Declares,inaClassblock,thename,arguments,andcodethatformthebodyofaPropertyprocedurethatsetsareferencetoanobject.
Syntax
[Public|Private]PropertySetname([arglist,]reference)[statements][ExitProperty][statements]EndProperty
ThePropertySetstatementsyntaxhastheseparts:
Part Description
Public IndicatesthatthePropertySetprocedureisaccessibletoallotherproceduresinallscripts.
Private IndicatesthatthePropertySetprocedureisaccessibleonlytootherproceduresintheClassblockwhereit'sdeclared.
nameNameofthePropertySetprocedure;followsstandardvariablenamingconventions,exceptthatthenamecanbethesameasaPropertyGetorPropertyLetprocedureinthesameClassblock.
arglist
ListofvariablesrepresentingargumentsthatarepassedtothePropertySetprocedurewhenitiscalled.Multipleargumentsareseparatedbycommas.Inaddition,thePropertySetprocedurewillalwayshaveonemoreargumentthanitscorrespondingPropertyGetprocedure.Thatargumentistheobjectbeingassignedtotheproperty.
referenceVariablecontainingtheobjectreferenceusedontherightsideoftheobjectreferenceassignment.
statements AnygroupofstatementstobeexecutedwithinthebodyofthePropertySetprocedure.
NoteVersionVersionEveryPropertySetstatementmustdefineatleastoneargumentfortheprocedureitdefines.Thatargument(orthelastargumentifthereismorethanone)containstheactualobjectreferenceforthepropertywhentheproceduredefinedbythePropertySetstatementisinvoked.Thatargumentisreferredtoasreferenceintheprecedingsyntax.
Remarks
IfnotexplicitlyspecifiedusingeitherPublicorPrivate,PropertySetproceduresarepublicbydefault,thatis,theyarevisibletoallotherproceduresinyourscript.ThevalueoflocalvariablesinaPropertySetprocedureisnotpreservedbetweencallstotheprocedure.
Youcan'tdefineaPropertySetprocedureinsideanyotherprocedure(e.g.FunctionorPropertyLet).
TheExitPropertystatementcausesanimmediateexitfromaPropertySetprocedure.ProgramexecutioncontinueswiththestatementthatfollowsthestatementthatcalledthePropertySetprocedure.AnynumberofExitPropertystatementscanappearanywhereinaPropertySetprocedure.
LikeaFunctionandPropertyGetprocedure,aPropertySetprocedureisaseparateprocedurethatcantakearguments,performaseriesofstatements,andchangethevalueofitsarguments.However,unlikeaFunctionandPropertyGetprocedure,bothofwhichreturnavalue,youcanonlyuseaPropertySetprocedureontheleftsideofanobjectreferenceassignment(Setstatement).
Microsoft®VisualBasic®ScriptingEditionPublicStatement
LanguageReferenceVersion2
SeeAlso
Description
Declarespublicvariablesandallocatesstoragespace.Declares,inaClassblock,aprivatevariable.
Syntax
Publicvarname[([subscripts])][,varname[([subscripts])]]...
ThePublicstatementsyntaxhastheseparts:
Part Descriptionvarname Nameofthevariable;followsstandardvariablenamingconventions.
subscripts
Dimensionsofanarrayvariable;upto60multipledimensionsmaybedeclared.Thesubscriptsargumentusesthefollowingsyntax:
upper[,upper]...
Thelowerboundofanarrayisalwayszero.
Remarks
Publicstatementvariablesareavailabletoallproceduresinallscripts.
Avariablethatreferstoanobjectmustbeassignedanexisting
objectusingtheSetstatementbeforeitcanbeused.Untilitisassignedanobject,thedeclaredobjectvariableisinitializedasEmpty.
YoucanalsousethePublicstatementwithemptyparenthesestodeclareadynamicarray.Afterdeclaringadynamicarray,usetheReDimstatementwithinaproceduretodefinethenumberofdimensionsandelementsinthearray.IfyoutrytoredeclareadimensionforanarrayvariablewhosesizewasexplicitlyspecifiedinaPrivate,Public,orDimstatement,anerroroccurs.
ThefollowingexampleillustratestheuseofthePublicstatement:
PublicMyNumber 'PublicVariantvariable.PublicMyArray(9)'Publicarrayvariable. 'MultiplePublicdeclarationsofVariantvariables.PublicMyNumber,MyVar,YourNumber
Microsoft®VisualBasic®ScriptingEditionRaiseMethod
LanguageReferenceVersion1
SeeAlsoAppliesto
Description
Generatesarun-timeerror.
Syntax
object.Raise(number,source,description,helpfile,helpcontext)
TheRaisemethodhastheseparts:
Part Descriptionobject AlwaystheErrobject.
numberALongintegersubtypethatidentifiesthenatureoftheerror.VBScripterrors(bothVBScript-definedanduser-definederrors)areintherange0–65535.
source
Astringexpressionnamingtheobjectorapplicationthatoriginallygeneratedtheerror.WhensettingthispropertyforanAutomationobject,usetheformproject.class.Ifnothingisspecified,theprogrammaticIDofthecurrentVBScriptprojectisused.
description
Astringexpressiondescribingtheerror.Ifunspecified,thevalueinnumberisexamined.IfitcanbemappedtoaVBScriptrun-timeerrorcode,astringprovidedbyVBScriptisusedasdescription.IfthereisnoVBScripterrorcorrespondingtonumber,agenericerrormessageisused.ThefullyqualifiedpathtotheHelpfileinwhichhelponthiserrorcanbefound.Ifunspecified,
helpfile VBScriptusesthefullyqualifieddrive,path,andfilenameoftheVBScriptHelpfile.
helpcontext
ThecontextIDidentifyingatopicwithinhelpfilethatprovideshelpfortheerror.Ifomitted,theVBScriptHelpfilecontextIDfortheerrorcorrespondingtothenumberpropertyisused,ifitexists.
Remarks
Alltheargumentsareoptionalexceptnumber.IfyouuseRaise,however,withoutspecifyingsomearguments,andthepropertysettingsoftheErrobjectcontainvaluesthathavenotbeencleared,thosevaluesbecomethevaluesforyourerror.
WhensettingthenumberpropertytoyourownerrorcodeinanAutomationobject,youaddyourerrorcodenumbertotheconstantvbObjectError.Forexample,togeneratetheerrornumber1050,assignvbObjectError+1050tothenumberproperty.
ThefollowingexampleillustratesuseoftheRaisemethod:
OnErrorResumeNextErr.Raise6'Raiseanoverflowerror.MsgBox("Error#"&CStr(Err.Number)&""&Err.Description)Err.Clear'Cleartheerror.
Microsoft®VisualBasic®ScriptingEdition
RandomizeStatement
LanguageReferenceVersion1
SeeAlso
Description
Initializestherandom-numbergenerator.
Syntax
Randomize[number]
Thenumberargumentcanbeanyvalidnumericexpression.
Remarks
RandomizeusesnumbertoinitializetheRndfunction'srandom-numbergenerator,givingitanewseedvalue.Ifyouomitnumber,thevaluereturnedbythesystemtimerisusedasthenewseedvalue.
IfRandomizeisnotused,theRndfunction(withnoarguments)usesthesamenumberasaseedthefirsttimeitiscalled,andthereafterusesthelastgeneratednumberasaseedvalue.
NoteTorepeatsequencesofrandomnumbers,callRndwithanegativeargumentimmediatelybeforeusingRandomizewithanumericargument.UsingRandomizewiththesamevaluefornumberdoesnotrepeattheprevioussequence.
ThefollowingexampleillustratesuseoftheRandomizestatement:
DimMyValue,ResponseRandomize 'Initializerandom-numbergenerator.
DoUntilResponse=vbNoMyValue=Int((6*Rnd)+1) 'Generaterandomvaluebetween1and6.MsgBoxMyValueResponse=MsgBox("Rollagain?",vbYesNo)Loop
Microsoft®VisualBasic®ScriptingEditionReDimStatement
LanguageReferenceVersion1
SeeAlso
Description
Declaresdynamic-arrayvariables,andallocatesorreallocatesstoragespaceatprocedurelevel.
Syntax
ReDim[Preserve]varname(subscripts)[,varname(subscripts)]...
TheReDimstatementsyntaxhastheseparts:
Part Description
Preserve Preservesthedatainanexistingarraywhenyouchangethesizeofthelastdimension.
varname Nameofthevariable;followsstandardvariablenamingconventions.
subscripts
Dimensionsofanarrayvariable;upto60multipledimensionsmaybedeclared.Thesubscriptsargumentusesthefollowingsyntax:
upper[,upper]...
Thelowerboundofanarrayisalwayszero.
Remarks
TheReDimstatementisusedtosizeorresizeadynamicarraythathasalreadybeenformallydeclaredusingaPrivate,Public,orDimstatementwithemptyparentheses(withoutdimensionsubscripts).YoucanusetheReDimstatementrepeatedlytochangethenumberofelementsand
dimensionsinanarray.
IfyouusethePreservekeyword,youcanresizeonlythelastarraydimension,andyoucan'tchangethenumberofdimensionsatall.Forexample,ifyourarrayhasonlyonedimension,youcanresizethatdimensionbecauseitisthelastandonlydimension.However,ifyourarrayhastwoormoredimensions,youcanchangethesizeofonlythelastdimensionandstillpreservethecontentsofthearray.
Thefollowingexampleshowshowyoucanincreasethesizeofthelastdimensionofadynamicarraywithouterasinganyexistingdatacontainedinthearray.
ReDimX(10,10,10)...ReDimPreserveX(10,10,15)
CautionIfyoumakeanarraysmallerthanitwasoriginally,dataintheeliminatedelementsislost.
Whenvariablesareinitialized,anumericvariableisinitializedto0andastringvariableisinitializedtoazero-lengthstring("").AvariablethatreferstoanobjectmustbeassignedanexistingobjectusingtheSetstatementbeforeitcanbeused.Untilitisassignedanobject,thedeclaredobjectvariablehasthespecialvalueNothing.
Microsoft®VisualBasic®ScriptingEditionRegExpObject
LanguageReferenceVersion5
SeeAlsoMethodsProperties
Description
Providessimpleregularexpressionsupport.
Remarks
ThefollowingcodeillustratestheuseoftheRegExpobject:
FunctionRegExpTest(patrn,strng)DimregEx,Match,Matches 'Createvariable.SetregEx=NewRegExp 'Createaregularexpression.regEx.Pattern=patrn 'Setpattern.regEx.IgnoreCase=True 'Setcaseinsensitivity.regEx.Global=True 'Setglobalapplicability.SetMatches=regEx.Execute(strng) 'Executesearch.ForEachMatchinMatches 'IterateMatchescollection.RetStr=RetStr&"Matchfoundatposition"RetStr=RetStr&Match.FirstIndex&".MatchValueis'"RetStr=RetStr&Match.Value&"'."&vbCRLFNextRegExpTest=RetStrEndFunction
MsgBox(RegExpTest("is.","IS1is2IS3is4"))
Microsoft®VisualBasic®ScriptingEditionRemStatement
LanguageReferenceVersion1
Description
Includesexplanatoryremarksinaprogram.
Syntax
Remcomment
or
'comment
Thecommentargumentisthetextofanycommentyouwanttoinclude.AftertheRemkeyword,aspaceisrequiredbeforecomment.
Remarks
Asshowninthesyntaxsection,youcanuseanapostrophe(')insteadoftheRemkeyword.IftheRemkeywordfollowsotherstatementsonaline,itmustbeseparatedfromthestatementsbyacolon.However,whenyouuseanapostrophe,thecolonisnotrequiredafterotherstatements.
ThefollowingexampleillustratestheuseoftheRemstatement:
DimMyStr1,MyStr2MyStr1="Hello":RemCommentafterastatementseparatedbyacolon.MyStr2="Goodbye"'Thisisalsoacomment;nocolonisneeded.RemCommentonalinewithnocode;nocolonisneeded.
Microsoft®VisualBasic®ScriptingEditionReplaceFunction
LanguageReferenceVersion2
SeeAlso
Description
Returnsastringinwhichaspecifiedsubstringhasbeenreplacedwithanothersubstringaspecifiednumberoftimes.
Syntax
Replace(expression,find,replacewith[,start[,count[,compare]]])
TheReplacefunctionsyntaxhastheseparts:
Part Description
expression Required.Stringexpressioncontainingsubstringtoreplace.
find Required.Substringbeingsearchedfor.replacewith Required.Replacementsubstring.
startOptional.Positionwithinexpressionwheresubstringsearchistobegin.Ifomitted,1isassumed.Mustbeusedinconjunctionwithcount.
count
Optional.Numberofsubstringsubstitutionstoperform.Ifomitted,thedefaultvalueis-1,whichmeansmakeallpossiblesubstitutions.Mustbeusedinconjunctionwithstart.
compare
Optional.Numericvalueindicatingthekindofcomparisontousewhenevaluatingsubstrings.SeeSettingssectionforvalues.Ifomitted,thedefaultvalueis0,whichmeansperformabinarycomparison.
Settings
Thecompareargumentcanhavethefollowingvalues:
Constant Value DescriptionvbBinaryCompare 0 Performabinarycomparison.vbTextCompare 1 Performatextualcomparison.
ReturnValues
Replacereturnsthefollowingvalues:
If Replacereturnsexpressioniszero-length Zero-lengthstring("").
expressionisNull Anerror.findiszero-length Copyofexpression.replacewithiszero-length
Copyofexpressionwithalloccurencesoffindremoved.
start>Len(expression) Zero-lengthstring.
countis0 Copyofexpression.
Remarks
ThereturnvalueoftheReplacefunctionisastring,withsubstitutionsmade,thatbeginsatthepositionspecifiedbystartandandconcludesattheendoftheexpressionstring.Itisnotacopyoftheoriginalstringfromstarttofinish.
ThefollowingexampleusestheReplacefunctiontoreturnastring:
DimMyStringMyString=Replace("XXpXXPXXp","p","Y") 'Abinarycomparisonstartingatthebeginning 'ofthestring.Returns"XXYXXPXXY".
MyString=Replace("XXpXXPXXp","p","Y", 'Atextualcomparisonstartingatposition3. 'Returns"YXXYXXY".3
Microsoft®VisualBasic®ScriptingEdition
ReplaceMethodLanguageReference
Version5
SeeAlsoAppliesto
Description
Replacestextfoundinaregularexpressionsearch.
Syntax
object.Replace(string1,string2)
TheReplacemethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaRegExpobject.string1 Required.String1isthetextstringinwhichthetextreplacementistooccur.
string2 Required.String2isthereplacementtextstring.
Remarks
TheactualpatternforthetextbeingreplacedissetusingthePatternpropertyoftheRegExpobject.
TheReplacemethodreturnsacopyofstring1withthetextofRegExp.Patternreplacedwithstring2.Ifnomatchisfound,acopyofstring1isreturnedunchanged.
ThefollowingcodeillustratesuseoftheReplacemethod:
FunctionReplaceTest(patrn,replStr)
DimregEx,str1 'Createvariables.str1="Thequickbrownfoxjumpedoverthelazydog."SetregEx=NewRegExp 'Createregularexpression.regEx.Pattern=patrn 'Setpattern.regEx.IgnoreCase=True 'Makecaseinsensitive.ReplaceTest=regEx.Replace(str1,replStr) 'Makereplacement.EndFunction
MsgBox(ReplaceTest("fox","cat")) 'Replace'fox'with'cat'.
Inaddition,theReplacemethodcanreplacesubexpressionsinthepattern.Thefollowingcalltothefunctionshowninthepreviousexampleswapseachpairofwordsintheoriginalstring:
MsgBox(ReplaceText("(\S+)(\s+)(\S+)","$3$2$1")) 'Swappairsofwords.
Microsoft®VisualBasic®ScriptingEditionRGBFunction
LanguageReferenceVersion2
Description
ReturnsawholenumberrepresentinganRGBcolorvalue.
Syntax
RGB(red,green,blue)
TheRGBfunctionhastheseparts:
Part Description
red Required.Numberintherange0-255representingtheredcomponentofthecolor.
green Required.Numberintherange0-255representingthegreencomponentofthecolor.
blue Required.Numberintherange0-255representingthebluecomponentofthecolor.
Remarks
ApplicationmethodsandpropertiesthatacceptacolorspecificationexpectthatspecificationtobeanumberrepresentinganRGBcolorvalue.AnRGBcolorvaluespecifiestherelativeintensityofred,green,andbluetocauseaspecificcolortobedisplayed.
Thelow-orderbytecontainsthevalueforred,themiddlebytecontainsthevalueforgreen,andthehigh-orderbytecontainsthevalueforblue.
Forapplicationsthatrequirethebyteordertobereversed,thefollowingfunctionwillprovidethesameinformationwiththebytesreversed:
FunctionRevRGB(red,green,blue)RevRGB=CLng(blue+(green*256)+(red*65536))EndFunction
ThevalueforanyargumenttoRGBthatexceeds255isassumedtobe255.
Microsoft®VisualBasic®ScriptingEditionRightFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsaspecifiednumberofcharactersfromtherightsideofastring.
Syntax
Right(string,length)
TheRightfunctionsyntaxhasthesearguments:
Part Description
string Stringexpressionfromwhichtherightmostcharactersarereturned.IfstringcontainsNull,Nullisreturned.
length
Numericexpressionindicatinghowmanycharacterstoreturn.If0,azero-lengthstringisreturned.Ifgreaterthanorequaltothenumberofcharactersinstring,theentirestringisreturned.
Remarks
Todeterminethenumberofcharactersinstring,usetheLenfunction.
ThefollowingexampleusestheRightfunctiontoreturnaspecifiednumberofcharactersfromtherightsideofastring:
DimAnyString,MyStrAnyString="HelloWorld"'Definestring.MyStr=Right(AnyString,1)'Returns"d".MyStr=Right(AnyString,6)'Returns"World".
MyStr=Right(AnyString,20)'Returns"HelloWorld".
NoteTheRightBfunctionisusedwithbytedatacontainedinastring.Insteadofspecifyingthenumberofcharacterstoreturn,lengthspecifiesthenumberofbytes.
Microsoft®VisualBasic®ScriptingEditionRndFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsarandomnumber.
Syntax
Rnd[(number)]
Thenumberargumentcanbeanyvalidnumericexpression.
Remarks
TheRndfunctionreturnsavaluelessthan1butgreaterthanorequalto0.ThevalueofnumberdetermineshowRndgeneratesarandomnumber:
Ifnumberis Rndgenerates
Lessthanzero Thesamenumbereverytime,usingnumberastheseed.
Greaterthanzero Thenextrandomnumberinthesequence.
Equaltozero Themostrecentlygeneratednumber.Notsupplied Thenextrandomnumberinthesequence.
Foranygiveninitialseed,thesamenumbersequenceisgeneratedbecauseeachsuccessivecalltotheRndfunctionusesthepreviousnumberasaseedforthenextnumberinthesequence.
BeforecallingRnd,usetheRandomizestatementwithoutanargumenttoinitializetherandom-numbergeneratorwithaseedbasedonthesystemtimer.
Toproducerandomintegersinagivenrange,usethisformula:
Int((upperbound-lowerbound+1)*Rnd+lowerboundHere,upperboundisthehighestnumberintherange,andlowerboundisthelowestnumberintherange.
NoteTorepeatsequencesofrandomnumbers,callRndwithanegativeargumentimmediatelybeforeusingRandomizewithanumericargument.UsingRandomizewiththesamevaluefornumberdoesnotrepeattheprevioussequence.
Microsoft®VisualBasic®ScriptingEditionRoundFunction
LanguageReferenceVersion2
SeeAlso
Description
Returnsanumberroundedtoaspecifiednumberofdecimalplaces.
Syntax
Round(expression[,numdecimalplaces])
TheRoundfunctionsyntaxhastheseparts:
Part Description
expression Required.Numericexpressionbeingrounded.
numdecimalplaces
Optional.Numberindicatinghowmanyplacestotherightofthedecimalareincludedintherounding.Ifomitted,integersarereturnedbytheRoundfunction.
Remarks
ThefollowingexampleusestheRoundfunctiontoroundanumbertotwodecimalplaces:
DimMyVar,pipi=3.14159MyVar=Round(pi,2)'MyVarcontains3.14.
Microsoft®VisualBasic®ScriptingEdition
ScriptEngineFunction
LanguageReferenceVersion2
SeeAlso
Description
Returnsastringrepresentingthescriptinglanguageinuse.
Syntax
ScriptEngine
ReturnValues
TheScriptEnginefunctioncanreturnanyofthefollowingstrings:
String Description
VBScript IndicatesthatMicrosoft®VisualBasic®ScriptingEditionisthecurrentscriptingengine.
JScript IndicatesthatMicrosoftJScript®isthecurrentscriptingengine.
VBA IndicatesthatMicrosoftVisualBasicforApplicationsisthecurrentscriptingengine.
Remarks
ThefollowingexampleusestheScriptEnginefunctiontoreturnastringdescribingthescriptinglanguageinuse:
FunctionGetScriptEngineInfoDimss="" 'Buildstringwithnecessaryinfo.
s=ScriptEngine&"Version"s=s&ScriptEngineMajorVersion&"."s=s&ScriptEngineMinorVersion&"."s=s&ScriptEngineBuildVersionGetScriptEngineInfo=s 'Returntheresults.EndFunction
Microsoft®VisualBasic®ScriptingEdition
ScriptEngineBuildVersionFunction
LanguageReferenceVersion2
SeeAlso
Description
Returnsthebuildversionnumberofthescriptingengineinuse.
Syntax
ScriptEngineBuildVersion
Remarks
ThereturnvaluecorrespondsdirectlytotheversioninformationcontainedintheDLLforthescriptinglanguageinuse.
ThefollowingexampleusestheScriptEngineBuildVersionfunctiontoreturnthebuildversionnumberofthescriptingengine:
FunctionGetScriptEngineInfoDimss="" 'Buildstringwithnecessaryinfo.s=ScriptEngine&"Version"s=s&ScriptEngineMajorVersion&"."s=s&ScriptEngineMinorVersion&"."s=s&ScriptEngineBuildVersionGetScriptEngineInfo=s 'Returntheresults.EndFunction
Microsoft®VisualBasic®ScriptingEdition
ScriptEngineMajorVersionFunction
LanguageReferenceVersion2
SeeAlso
Description
Returnsthemajorversionnumberofthescriptingengineinuse.
Syntax
ScriptEngineMajorVersion
Remarks
ThereturnvaluecorrespondsdirectlytotheversioninformationcontainedintheDLLforthescriptinglanguageinuse.
ThefollowingexampleusestheScriptEngineMajorVersionfunctiontoreturntheversionnumberofthescriptingengine:
FunctionGetScriptEngineInfoDimss="" 'Buildstringwithnecessaryinfo.s=ScriptEngine&"Version"s=s&ScriptEngineMajorVersion&"."s=s&ScriptEngineMinorVersion&"."s=s&ScriptEngineBuildVersionGetScriptEngineInfo=s 'Returntheresults.EndFunction
Microsoft®VisualBasic®ScriptingEdition
ScriptEngineMinorVersionFunction
LanguageReferenceVersion2
SeeAlso
Description
Returnstheminorversionnumberofthescriptingengineinuse.
Syntax
ScriptEngineMinorVersion
Remarks
ThereturnvaluecorrespondsdirectlytotheversioninformationcontainedintheDLLforthescriptinglanguageinuse.
ThefollowingexampleusestheScriptEngineMinorVersionfunctiontoreturntheminorversionnumberofthescriptingengine:
FunctionGetScriptEngineInfoDimss="" 'Buildstringwithnecessaryinfo.s=ScriptEngine&"Version"s=s&ScriptEngineMajorVersion&"."s=s&ScriptEngineMinorVersion&"."s=s&ScriptEngineBuildVersionGetScriptEngineInfo=s 'Returntheresults.EndFunction
Microsoft®VisualBasic®ScriptingEditionSecondFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsawholenumberbetween0and59,inclusive,representingthesecondoftheminute.
Syntax
Second(time)
Thetimeargumentisanyexpressionthatcanrepresentatime.IftimecontainsNull,Nullisreturned.
Remarks
ThefollowingexampleusestheSecondfunctiontoreturnthecurrentsecond:
DimMySecMySec=Second(Now) 'MySeccontainsthenumberrepresenting 'thecurrentsecond.
Microsoft®VisualBasic®ScriptingEditionSelectCaseStatement
LanguageReferenceVersion1
SeeAlso
Description
Executesoneofseveralgroupsofstatements,dependingonthevalueofanexpression.
Syntax
SelectCasetestexpression[Caseexpressionlist-n[statements-n]]...[CaseElseexpressionlist-n[elsestatements-n]]EndSelect
TheSelectCasestatementsyntaxhastheseparts:
Part Descriptiontestexpression Anynumericorstringexpression.expressionlist-n
RequiredifCaseappears.Delimitedlistofoneormoreexpressions.
statements-nOneormorestatementsexecutediftestexpressionmatchesanypartofexpressionlist-n.
elsestatements-n
Oneormorestatementsexecutediftestexpressiondoesn'tmatchanyoftheCaseclauses.
Remarks
IftestexpressionmatchesanyCaseexpressionlistexpression,thestatementsfollowingthatCaseclauseareexecuteduptothenextCaseclause,orforthelastclause,uptoEndSelect.ControlthenpassestothestatementfollowingEndSelect.IftestexpressionmatchesanexpressionlistexpressioninmorethanoneCaseclause,onlythestatementsfollowingthefirstmatchareexecuted.
TheCaseElseclauseisusedtoindicatetheelsestatementstobeexecutedifnomatchisfoundbetweenthetestexpressionandanexpressionlistinanyoftheotherCaseselections.Althoughnotrequired,itisagoodideatohaveaCaseElsestatementinyourSelectCaseblocktohandleunforeseentestexpressionvalues.IfnoCaseexpressionlistmatchestestexpressionandthereisnoCaseElsestatement,executioncontinuesatthestatementfollowingEndSelect.
SelectCasestatementscanbenested.EachnestedSelectCasestatementmusthaveamatchingEndSelectstatement.
ThefollowingexampleillustratestheuseoftheSelectCasestatement:
DimColor,MyVarSubChangeBackground(Color) MyVar=lcase(Color) SelectCaseMyVarCase"red"document.bgColor="red"Case"green"document.bgColor="green"Case"blue"document.bgColor="blue"CaseElseMsgBox"pickanothercolor"EndSelectEndSub
Microsoft®VisualBasic®ScriptingEditionSetStatement
LanguageReferenceVersion1
SeeAlso
Description
Assignsanobjectreferencetoavariableorproperty,orassociatesaprocedurereferencewithanevent.
Syntax1
Setobjectvar={objectexpression|Newclassname|Nothing}
Syntax2
Setobject.eventname=GetRef(procname)
TheSetstatementsyntaxhastheseparts:
Part Description
objectvar Required.Nameofthevariableorproperty;followsstandardvariablenamingconventions.
objectexpressionOptional.Expressionconsistingofthenameofanobject,anotherdeclaredvariableofthesameobjecttype,orafunctionormethodthatreturnsanobjectofthesameobjecttype.
NewKeywordusedtocreateanewinstanceofaclass.Ifobjectvarcontainedareferencetoanobject,thatreferenceisreleasedwhenthenewoneisassigned.TheNewkeywordcanonlybeusedtocreateaninstanceofaclass.
classname Optional.Nameoftheclassbeingcreated.AclassanditsmembersaredefinedusingtheClassstatement.
Nothing
Optional.Discontinuesassociationofobjectvarwithanyspecificobjectorclass.AssigningobjectvartoNothingreleasesallthesystemandmemoryresourcesassociatedwiththepreviouslyreferencedobjectwhennoothervariablereferstoit.
object Required.Nameoftheobjectwithwhicheventisassociated.
event Required.Nameoftheeventtowhichthefunctionistobebound.
procname Required.StringcontainingthenameoftheSuborFunctionbeingassociatedwiththeevent.
Remarks
Tobevalid,objectvarmustbeanobjecttypeconsistentwiththeobjectbeingassignedtoit.
TheDim,Private,Public,orReDimstatementsonlydeclareavariablethatreferstoanobject.NoactualobjectisreferredtountilyouusetheSetstatementtoassignaspecificobject.
Generally,whenyouuseSettoassignanobjectreferencetoavariable,nocopyoftheobjectiscreatedforthatvariable.Instead,areferencetotheobjectiscreated.Morethanoneobjectvariablecanrefertothesameobject.Becausethesevariablesarereferencesto(ratherthancopiesof)theobject,anychangeintheobjectisreflectedinallvariablesthatrefertoit.
FunctionShowFreeSpace(drvPath)Dimfso,d,sSetfso=CreateObject("Scripting.FileSystemObject")Setd=fso.GetDrive(fso.GetDriveName(drvPath))s="Drive"&UCase(drvPath)&"-"s=s&d.VolumeName&"<BR>"s=s&"FreeSpace:"&FormatNumber(d.FreeSpace/1024,0)s=s&"Kbytes"ShowFreeSpace=sEndFunction
UsingtheNewkeywordallowsyoutoconcurrentlycreateaninstanceofaclassandassignittoanobjectreferencevariable.Thevariabletowhichtheinstanceoftheclassisbeingassigned
mustalreadyhavebeendeclaredwiththeDim(orequivalent)statement.
RefertothedocumentationfortheGetReffunctionforinformationonusingSettoassociateaprocedurewithanevent.
Microsoft®VisualBasic®ScriptingEditionSgnFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsanintegerindicatingthesignofanumber.
Syntax
Sgn(number)
Thenumberargumentcanbeanyvalidnumericexpression.
ReturnValues
TheSgnfunctionhasthefollowingreturnvalues:
Ifnumberis SgnreturnsGreaterthanzero 1Equaltozero 0Lessthanzero -1
Remarks
ThesignofthenumberargumentdeterminesthereturnvalueoftheSgnfunction.
ThefollowingexampleusestheSgnfunctiontodeterminethesignofanumber:
DimMyVar1,MyVar2,MyVar3,MySignMyVar1=12:MyVar2=-2.4:MyVar3=0MySign=Sgn(MyVar1)'Returns1.
MySign=Sgn(MyVar2)'Returns-1.MySign=Sgn(MyVar3)'Returns0.
Microsoft®VisualBasic®ScriptingEditionSinFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsthesineofanangle.
Syntax
Sin(number)
Thenumberargumentcanbeanyvalidnumericexpressionthatexpressesanangleinradians.
Remarks
TheSinfunctiontakesanangleandreturnstheratiooftwosidesofarighttriangle.Theratioisthelengthofthesideoppositetheangledividedbythelengthofthehypotenuse.Theresultliesintherange-1to1.
Toconvertdegreestoradians,multiplydegreesbypi/180.Toconvertradianstodegrees,multiplyradiansby180/pi.
ThefollowingexampleusestheSinfunctiontoreturnthesineofanangle:
DimMyAngle,MyCosecantMyAngle=1.3'Defineangleinradians.MyCosecant=1/Sin(MyAngle)'Calculatecosecant.
Microsoft®VisualBasic®ScriptingEditionSourceProperty
LanguageReferenceVersion1
SeeAlsoAppliesto
Description
Returnsorsetsthenameoftheobjectorapplicationthatoriginallygeneratedtheerror.
Syntax
object.Source[=stringexpression]
TheSourcepropertysyntaxhastheseparts:
Part Descriptionobject AlwaystheErrobject.
stringexpression Astringexpressionrepresentingtheapplicationthatgeneratedtheerror.
Remarks
TheSourcepropertyspecifiesastringexpressionthatisusuallytheclassnameorprogrammaticIDoftheobjectthatcausedtheerror.UseSourcetoprovideyouruserswithinformationwhenyourcodeisunabletohandleanerrorgeneratedinanaccessedobject.Forexample,ifyouaccessMicrosoftExcelanditgeneratesaDivisionbyzeroerror,MicrosoftExcelsetsErr.NumbertoitserrorcodeforthaterrorandsetsSourcetoExcel.Application.NotethatiftheerrorisgeneratedinanotherobjectcalledbyMicrosoftExcel,ExcelinterceptstheerrorandsetsErr.NumbertoitsowncodeforDivisionbyzero.However,itleavestheotherErrobject(includingSource)assetbytheobjectthatgeneratedtheerror.
Sourcealwayscontainsthenameoftheobjectthatoriginallygeneratedtheerror—yourcodecantrytohandletheerroraccordingtotheerrordocumentationoftheobjectyouaccessed.Ifyourerror
handlerfails,youcanusetheErrobjectinformationtodescribetheerrortoyouruser,usingSourceandtheotherErrtoinformtheuserwhichobjectoriginallycausedtheerror,itsdescriptionoftheerror,andsoforth.
Whengeneratinganerrorfromcode,Sourceisyourapplication'sprogrammaticID.
ThefollowingcodeillustratesuseoftheSourceproperty:
OnErrorResumeNextErr.Raise6'Raiseanoverflowerror.MsgBox("Error#"&CStr(Err.Number)&""&Err.Description&Err.Clear'Cleartheerror.
Microsoft®VisualBasic®ScriptingEditionSpaceFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsastringconsistingofthespecifiednumberofspaces.
Syntax
Space(number)
Thenumberargumentisthenumberofspacesyouwantinthestring.
Remarks
ThefollowingexampleusestheSpacefunctiontoreturnastringconsistingofaspecifiednumberofspaces:
DimMyStringMyString=Space(10)'Returnsastringwith10spaces.MyString="Hello"&Space(10)&"World"'Insert10spacesbetweentwostrings.
Microsoft®VisualBasic®ScriptingEditionSplitFunction
LanguageReferenceVersion2
SeeAlso
Description
Returnsazero-based,one-dimensionalarraycontainingaspecifiednumberofsubstrings.
Syntax
Split(expression[,delimiter[,count[,compare]]])
TheSplitfunctionsyntaxhastheseparts:
Part Description
expression
Required.Stringexpressioncontainingsubstringsanddelimiters.Ifexpressionisazero-lengthstring,Splitreturnsanemptyarray,thatis,anarraywithnoelementsandnodata.
delimiter
Optional.Stringcharacterusedtoidentifysubstringlimits.Ifomitted,thespacecharacter("")isassumedtobethedelimiter.Ifdelimiterisazero-lengthstring,asingle-elementarraycontainingtheentireexpressionstringisreturned.
count Optional.Numberofsubstringstobereturned;-1indicatesthatallsubstringsarereturned.
compareOptional.Numericvalueindicatingthekindofcomparisontousewhenevaluatingsubstrings.SeeSettingssectionforvalues.
Settings
Thecompareargumentcanhavethefollowingvalues:
Constant Value DescriptionvbBinaryCompare 0 Performabinarycomparison.vbTextCompare 1 Performatextualcomparison.
Remarks
ThefollowingexampleusestheSplitfunctiontoreturnanarrayfromastring.Thefunctionperformsatextualcomparisonofthedelimiter,andreturnsallofthesubstrings.
DimMyString,MyArray,MsgMyString="VBScriptXisXfun!"MyArray=Split(MyString,"x",-1,1)'MyArray(0)contains"VBScript".'MyArray(1)contains"is".'MyArray(2)contains"fun!".Msg=MyArray(0)&""&MyArray(1)Msg=Msg&""&MyArray(2)MsgBoxMsg
Description
Returnsthesquarerootofanumber.
Syntax
Sqr(number)
Thenumberargumentcanbeanyvalidnumericexpressiongreaterthanorequalto0.
Remarks
ThefollowingexampleusestheSqrfunctiontocalculatethesquarerootofanumber:
DimMySqrMySqr=Sqr(4)'Returns2.MySqr=Sqr(23)'Returns4.79583152331272.MySqr=Sqr(0)'Returns0.MySqr=Sqr(-4)'Generatesarun-timeerror.
Microsoft®VisualBasic®ScriptingEditionSqrFunction
LanguageReferenceVersion1
Microsoft®VisualBasic®ScriptingEdition
StrCompFunctionLanguageReference
Version1
Description
Returnsavalueindicatingtheresultofastringcomparison.
Syntax
StrComp(string1,string2[,compare])
TheStrCompfunctionsyntaxhasthesearguments:
Part Descriptionstring1 Required.Anyvalidstringexpression.string2 Required.Anyvalidstringexpression.
compare
Optional.Numericvalueindicatingthekindofcomparisontousewhenevaluatingstrings.Ifomitted,abinarycomparisonisperformed.SeeSettingssectionforvalues.
Settings
Thecompareargumentcanhavethefollowingvalues:
Constant Value DescriptionvbBinaryCompare 0 Performabinarycomparison.vbTextCompare 1 Performatextualcomparison.
ReturnValues
TheStrCompfunctionhasthefollowingreturnvalues:
If StrCompreturnsstring1islessthanstring2 -1string1isequaltostring2 0string1isgreaterthanstring2 1string1orstring2isNull Null
Remarks
ThefollowingexampleusestheStrCompfunctiontoreturntheresultsofastringcomparison.Ifthethirdargumentis1,atextualcomparisonisperformed;ifthethirdargumentis0oromitted,abinarycomparisonisperformed.
DimMyStr1,MyStr2,MyCompMyStr1="ABCD":MyStr2="abcd"'Definevariables.MyComp=StrComp(MyStr1,MyStr2,1)'Returns0.MyComp=StrComp(MyStr1,MyStr2,0)'Returns-1.MyComp=StrComp(MyStr2,MyStr1)'Returns1.
Microsoft®VisualBasic®ScriptingEditionStringConstants
LanguageReferenceVersion2
SeeAlso
SincetheseconstantsarebuiltintoVBScript,youdon'thavetodefinethembeforeusingthem.Usethemanywhereinyourcodetorepresentthevaluesshownforeach.
Constant Value DescriptionvbCr Chr(13) Carriagereturn.
vbCrLf Chr(13)&Chr(10) Carriagereturn–linefeedcombination.
vbFormFeed Chr(12) Formfeed;notusefulinMicrosoftWindows.vbLf Chr(10) Linefeed.
vbNewLineChr(13)&Chr(10)orChr(10)
Platform-specificnewlinecharacter;whateverisappropriatefortheplatform.
vbNullChar Chr(0) Characterhavingthevalue0.
vbNullString Stringhavingvalue0
Notthesameasazero-lengthstring("");usedforcallingexternalprocedures.
vbTab Chr(9) Horizontaltab.vbVerticalTab Chr(11) Verticaltab;notusefulinMicrosoftWindows.
Microsoft®VisualBasic®ScriptingEditionStringFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsarepeatingcharacterstringofthelengthspecified.
Syntax
String(number,character)
TheStringfunctionsyntaxhasthesearguments:
Part Description
number Lengthofthereturnedstring.IfnumbercontainsNull,Nullisreturned.
character
Charactercodespecifyingthecharacterorstringexpressionwhosefirstcharacterisusedtobuildthereturnstring.IfcharactercontainsNull,Nullisreturned.
Remarks
Ifyouspecifyanumberforcharactergreaterthan255,Stringconvertsthenumbertoavalidcharactercodeusingtheformula:
characterMod256ThefollowingexampleusestheStringfunctiontoreturnrepeatingcharacterstringsofthelengthspecified:
DimMyStringMyString=String(5,"*")'Returns"*****".MyString=String(5,42)'Returns"*****".MyString=String(10,"ABC")'Returns"AAAAAAAAAA".
Microsoft®VisualBasic®ScriptingEdition
StrReverseFunction
LanguageReferenceVersion2
Description
Returnsastringinwhichthecharacterorderofaspecifiedstringisreversed.
Syntax
StrReverse(string1)
Thestring1argumentisthestringwhosecharactersaretobereversed.Ifstring1isazero-lengthstring(""),azero-lengthstringisreturned.Ifstring1isNull,anerroroccurs.
Remarks
ThefollowingexampleusestheStrReversefunctiontoreturnastringinreverseorder:
DimMyStrMyStr=StrReverse("VBScript")'MyStrcontains"tpircSBV".
Microsoft®VisualBasic®ScriptingEditionSubStatement
LanguageReferenceVersion1
SeeAlso
Description
Declaresthename,arguments,andcodethatformthebodyofaSubprocedure.
Syntax
[Public[Default]|Private]Subname[(arglist)][statements][ExitSub][statements]EndSub
TheSubstatementsyntaxhastheseparts:
Part DescriptionPublic IndicatesthattheSubprocedureisaccessibletoallotherproceduresinallscripts.
DefaultUsedonlywiththePublickeywordinaClassblocktoindicatethattheSubprocedureisthedefaultmethodfortheclass.AnerroroccursifmorethanoneDefaultprocedureisspecifiedinaclass.
Private IndicatesthattheSubprocedureisaccessibleonlytootherproceduresinthescriptwhereitisdeclared.
name NameoftheSub;followsstandardvariablenamingconventions.
arglist ListofvariablesrepresentingargumentsthatarepassedtotheSubprocedurewhenitiscalled.Multiplevariablesareseparatedbycommas.
statements AnygroupofstatementstobeexecutedwithinthebodyoftheSubprocedure.
Thearglistargumenthasthefollowingsyntaxandparts:
[ByVal|ByRef]varname[()]
Part DescriptionByVal Indicatesthattheargumentispassedbyvalue.
ByRef Indicatesthattheargumentispassedbyreference.
varname Nameofthevariablerepresentingtheargument;followsstandardvariablenamingconventions.
Remarks
IfnotexplicitlyspecifiedusingeitherPublicorPrivate,Subproceduresarepublicbydefault,thatis,theyarevisibletoallotherproceduresinyourscript.ThevalueoflocalvariablesinaSubprocedureisnotpreservedbetweencallstotheprocedure.
Youcan'tdefineaSubprocedureinsideanyotherprocedure(e.g.FunctionorPropertyGet).
TheExitSubstatementcausesanimmediateexitfromaSubprocedure.ProgramexecutioncontinueswiththestatementthatfollowsthestatementthatcalledtheSubprocedure.AnynumberofExitSubstatementscanappearanywhereinaSubprocedure.
LikeaFunctionprocedure,aSubprocedureisaseparateprocedurethatcantakearguments,performaseriesofstatements,andchangethevalueofitsarguments.However,unlikeaFunctionprocedure,whichreturnsavalue,aSubprocedurecan'tbeusedinanexpression.
YoucallaSubprocedureusingtheprocedurenamefollowedbytheargumentlist.SeetheCallstatementforspecificinformationonhowtocallSubprocedures.
CautionSubprocedurescanberecursive,thatis,theycancallthemselvestoperformagiven
task.However,recursioncanleadtostackoverflow.
VariablesusedinSubproceduresfallintotwocategories:thosethatareexplicitlydeclaredwithintheprocedureandthosethatarenot.Variablesthatareexplicitlydeclaredinaprocedure(usingDimortheequivalent)arealwayslocaltotheprocedure.Variablesthatareusedbutnotexplicitlydeclaredinaprocedurearealsolocal,unlesstheyareexplicitlydeclaredatsomehigherleveloutsidetheprocedure.
CautionAprocedurecanuseavariablethatisnotexplicitlydeclaredintheprocedure,butanamingconflictcanoccurifanythingyouhavedefinedatthescriptlevelhasthesamename.Ifyourprocedurereferstoanundeclaredvariablethathasthesamenameasanotherprocedure,constantorvariable,itisassumedthatyourprocedureisreferringtothatscript-levelname.Toavoidthiskindofconflict,useanOptionExplicitstatementtoforceexplicitdeclarationofvariables.
Microsoft®VisualBasic®ScriptingEditionTanFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsthetangentofanangle.
Syntax
Tan(number)
Thenumberargumentcanbeanyvalidnumericexpressionthatexpressesanangleinradians.
Remarks
Tantakesanangleandreturnstheratiooftwosidesofarighttriangle.Theratioisthelengthofthesideoppositetheangledividedbythelengthofthesideadjacenttotheangle.
Toconvertdegreestoradians,multiplydegreesbypi/180.Toconvertradianstodegrees,multiplyradiansby180/pi.
ThefollowingexampleusestheTanfunctiontoreturnthetangentofanangle:
DimMyAngle,MyCotangentMyAngle=1.3'Defineangleinradians.MyCotangent=1/Tan(MyAngle)'Calculatecotangent.
Microsoft®VisualBasic®ScriptingEdition
TerminateEventLanguageReference
Version5
SeeAlsoAppliesTo
Description
Occurswhenaninstanceoftheassociatedclassisterminated.
Syntax
PrivateSubClass_Terminate()statementsEndSub
Thestatementspartconsistsofzeroormorecodestatementstoberunwhentheclassisinitialized.
Remarks
ThefollowingexampleillustratestheuseoftheTerminateevent:
ClassTestClassPrivateSubClass_Initialize 'SetupInitializeevent.MsgBox("TestClassstarted")EndSubPrivateSubClass_Terminate 'SetupTerminateevent.MsgBox("TestClassterminated")EndSubEndClass
SetX=NewTestClass 'CreateaninstanceofTestClass.SetX=Nothing 'Destroytheinstance.
Microsoft®VisualBasic®ScriptingEdition
TestMethodLanguageReference
Version5
SeeAlsoAppliesto
Description
ExecutesaregularexpressionsearchagainstaspecifiedstringandreturnsaBooleanvaluethatindicatesifapatternmatchwasfound.
Syntax
object.Test(string)
TheExecutemethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaRegExpobject.string Required.Thetextstringuponwhichtheregularexpressionisexecuted.
Remarks
TheactualpatternfortheregularexpressionsearchissetusingthePatternpropertyoftheRegExpobject.TheRegExp.GlobalpropertyhasnoeffectontheTestmethod.
TheTestmethodreturnsTrueifapatternmatchisfound;Falseifnomatchisfound.
ThefollowingcodeillustratestheuseoftheTestmethod:
FunctionRegExpTest(patrn,strng)DimregEx,retVal 'Createvariable.SetregEx=NewRegExp 'Createregularexpression.regEx.Pattern=patrn 'Setpattern.regEx.IgnoreCase=False 'Setcasesensitivity.retVal=regEx.Test(strng) 'Executethesearchtest.IfretValThenRegExpTest="Oneormorematcheswerefound."ElseRegExpTest="Nomatchwasfound."EndIfEndFunction
MsgBox(RegExpTest("is.","IS1is2IS3is4"))
Microsoft®VisualBasic®ScriptingEditionTimeFunction
LanguageReferenceVersion1
SeeAlso
Description
ReturnsaVariantofsubtypeDateindicatingthecurrentsystemtime.
Syntax
Time
Remarks
ThefollowingexampleusestheTimefunctiontoreturnthecurrentsystemtime:
DimMyTimeMyTime=Time'Returncurrentsystemtime.
Microsoft®VisualBasic®ScriptingEditionTimerFunction
LanguageReferenceVersion5
SeeAlso
Description
Returnsthenumberofsecondsthathaveelapsedsince12:00AM(midnight).
Syntax
Timer
Remarks
ThefollowingexampleusestheTimerfunctiontodeterminethetimeittakestoiterateaFor...NextloopNtimes:
FunctionTimeIt(N)DimStartTime,EndTimeStartTime=TimerForI=1ToNNextEndTime=TimerTimeIt=EndTime-StartTimeEndFunction
Microsoft®VisualBasic®ScriptingEdition
TimeSerialFunction
LanguageReferenceVersion1
SeeAlso
Description
ReturnsaVariantofsubtypeDatecontainingthetimeforaspecifichour,minute,andsecond.
Syntax
TimeSerial(hour,minute,second)
TheTimeSerialfunctionsyntaxhasthesearguments:
Part Description
hour Numberbetween0(12:00A.M.)and23(11:00P.M.),inclusive,oranumericexpression.
minute Anynumericexpression.second Anynumericexpression.
Remarks
Tospecifyatime,suchas11:59:59,therangeofnumbersforeachTimeSerialargumentshouldbeintheacceptedrangefortheunit;thatis,0–23forhoursand0–59forminutesandseconds.However,youcanalsospecifyrelativetimesforeachargumentusinganynumericexpressionthatrepresentssomenumberofhours,minutes,orsecondsbeforeorafteracertaintime.
Thefollowingexampleusesexpressionsinsteadofabsolutetimenumbers.TheTimeSerialfunctionreturnsatimefor15minutesbefore(-15)sixhoursbeforenoon(12-6),or5:45:00A.M.
DimMyTime1
MyTime1=TimeSerial(12-6,-15,0)'Returns5:45:00AM.Whenanyargumentexceedstheacceptedrangeforthatargument,itincrementstothenextlargerunitasappropriate.Forexample,ifyouspecify75minutes,itisevaluatedasonehourand15minutes.However,ifanysingleargumentisoutsidetherange-32,768to32,767,orifthetimespecifiedbythethreearguments,eitherdirectlyorbyexpression,causesthedatetofalloutsidetheacceptablerangeofdates,anerroroccurs.
Microsoft®VisualBasic®ScriptingEdition
TimeValueFunction
LanguageReferenceVersion1
SeeAlso
Description
ReturnsaVariantofsubtypeDatecontainingthetime.
Syntax
TimeValue(time)
Thetimeargumentisusuallyastringexpressionrepresentingatimefrom0:00:00(12:00:00A.M.)to23:59:59(11:59:59P.M.),inclusive.However,timecanalsobeanyexpressionthatrepresentsatimeinthatrange.IftimecontainsNull,Nullisreturned.
Remarks
Youcanentervalidtimesusinga12-houror24-hourclock.Forexample,"2:24PM"and"14:24"arebothvalidtimearguments.Ifthetimeargumentcontainsdateinformation,TimeValuedoesn'treturnthedateinformation.However,iftimeincludesinvaliddateinformation,anerroroccurs.
ThefollowingexampleusestheTimeValuefunctiontoconvertastringtoatime.YoucanalsousedateliteralstodirectlyassignatimetoaVariant(forexample,MyTime=#4:35:17PM#).
DimMyTimeMyTime=TimeValue("4:35:17PM")'MyTimecontains4:35:17PM.
Microsoft®VisualBasic®ScriptingEditionTrueLanguageReference
Version1
SeeAlso
Description
TheTruekeywordhasavalueequalto-1.
Microsoft®VisualBasic®ScriptingEdition
TypeNameFunction
LanguageReferenceVersion2
SeeAlso
Description
ReturnsastringthatprovidesVariantsubtypeinformationaboutavariable.
Syntax
TypeName(varname)
Therequiredvarnameargumentcanbeanyvariable.
ReturnValues
TheTypeNamefunctionhasthefollowingreturnvalues:
Value DescriptionByte BytevalueInteger IntegervalueLong LongintegervalueSingle Single-precisionfloating-pointvalueDouble Double-precisionfloating-pointvalueCurrency CurrencyvalueDecimal DecimalvalueDate DateortimevalueString CharacterstringvalueBoolean Booleanvalue;TrueorFalseEmpty UnitializedNull Novaliddata
<object;type>
Actualtypenameofanobject
Object GenericobjectUnknown Unknownobjecttype
Nothing Objectvariablethatdoesn'tyetrefertoanobjectinstance
Error Error
Remarks
ThefollowingexampleusestheTypeNamefunctiontoreturninformationaboutavariable:
DimArrayVar(4),MyTypeNullVar=Null 'AssignNullvalue.
MyType=TypeName("VBScript")'Returns"String".MyType=TypeName(4)'Returns"Integer".MyType=TypeName(37.50)'Returns"Double".MyType=TypeName(NullVar)'Returns"Null".MyType=TypeName(ArrayVar)'Returns"Variant()".
Microsoft®VisualBasic®ScriptingEditionUBoundFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsthelargestavailablesubscriptfortheindicateddimensionofanarray.
Syntax
UBound(arrayname[,dimension])
TheUBoundfunctionsyntaxhastheseparts:
Part Description
arrayname Required.Nameofthearrayvariable;followsstandardvariablenamingconventions.
dimension
Optional.Wholenumberindicatingwhichdimension'supperboundisreturned.Use1forthefirstdimension,2forthesecond,andsoon.Ifdimensionisomitted,1isassumed.
Remarks
TheUBoundfunctionisusedwiththeLBoundfunctiontodeterminethesizeofanarray.UsetheLBoundfunctiontofindthelowerlimitofanarraydimension.
Thelowerboundforanydimensionisalways0.Asaresult,UBoundreturnsthefollowingvaluesforanarraywiththesedimensions:
DimA(100,3,4)
Statement ReturnValueUBound(A,1) 100UBound(A,2) 3UBound(A,3) 4
Microsoft®VisualBasic®ScriptingEditionUCaseFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsastringthathasbeenconvertedtouppercase.
Syntax
UCase(string)
Thestringargumentisanyvalidstringexpression.IfstringcontainsNull,Nullisreturned.
Remarks
Onlylowercaselettersareconvertedtouppercase;alluppercaselettersandnonlettercharactersremainunchanged.
ThefollowingexampleusestheUCasefunctiontoreturnanuppercaseversionofastring:
DimMyWordMyWord=UCase("HelloWorld")'Returns"HELLOWORLD".
Microsoft®VisualBasic®ScriptingEditionValueProperty
LanguageReferenceVersion5
SeeAlsoAppliesTo
Description
Returnsthevalueortextofamatchfoundinasearchstring.
Syntax
object.Value
TheobjectargumentisalwaysaMatchobject.
Remarks
ThefollowingcodeillustratestheuseoftheValueproperty:
FunctionRegExpTest(patrn,strng)DimregEx,Match,Matches 'Createvariable.SetregEx=NewRegExp 'Createregularexpression.regEx.Pattern=patrn 'Setpattern.regEx.IgnoreCase=True 'Setcaseinsensitivity.regEx.Global=True 'Setglobalapplicability.SetMatches=regEx.Execute(strng) 'Executesearch.ForEachMatchinMatches 'IterateMatchescollection.RetStr=RetStr&"Match"&I&"foundatposition"RetStr=RetStr&Match.FirstIndex&".MatchValueis"'RetStr=RetStr&Match.Value&"'."&vbCRLF
NextRegExpTest=RetStrEndFunction
MsgBox(RegExpTest("is.","IS1is2IS3is4"))
Microsoft®VisualBasic®ScriptingEdition
VarTypeConstants
LanguageReferenceVersion2
SeeAlso
Theseconstantsareonlyavailablewhenyourprojecthasanexplicitreferencetotheappropriatetypelibrarycontainingtheseconstantdefinitions.ForVBScript,youmustexplicitlydeclaretheseconstantsinyourcode.
Constant Value DescriptionvbEmpty 0 Uninitialized(default)vbNull 1 ContainsnovaliddatavbInteger 2 IntegersubtypevbLong 3 LongsubtypevbSingle 4 SinglesubtypevbSingle 5 DoublesubtypevbCurrency 6 CurrencysubtypevbDate 7 DatesubtypevbString 8 StringsubtypevbObject 9 ObjectvbError 10 ErrorsubtypevbBoolean 11 BooleansubtypevbVariant 12 Variant(usedonlyforarraysofvariants)vbDataObject 13 DataaccessobjectvbDecimal 14 DecimalsubtypevbByte 17 BytesubtypevbArray 8192 Array
Microsoft®VisualBasic®ScriptingEdition
VarTypeFunctionLanguageReference
Version1
SeeAlso
Description
Returnsavalueindicatingthesubtypeofavariable.
Syntax
VarType(varname)
Thevarnameargumentcanbeanyvariable.
ReturnValues
TheVarTypefunctionreturnsthefollowingvalues:
Constant Value DescriptionvbEmpty 0 Empty(uninitialized)vbNull 1 Null(novaliddata)vbInteger 2 IntegervbLong 3 LongintegervbSingle 4 Single-precisionfloating-pointnumbervbDouble 5 Double-precisionfloating-pointnumbervbCurrency 6 CurrencyvbDate 7 DatevbString 8 StringvbObject 9 AutomationobjectvbError 10 ErrorvbBoolean 11 Boolean
vbVariant 12 Variant(usedonlywitharraysofVariants)
vbDataObject 13 Adata-accessobjectvbByte 17 BytevbArray 8192 Array
NoteTheseconstantsarespecifiedbyVBScript.Asaresult,thenamescanbeusedanywhereinyourcodeinplaceoftheactualvalues.
Remarks
TheVarTypefunctionneverreturnsthevalueforArraybyitself.Itisalwaysaddedtosomeothervaluetoindicateanarrayofaparticulartype.ThevalueforVariantisonlyreturnedwhenithasbeenaddedtothevalueforArraytoindicatethattheargumenttotheVarTypefunctionisanarray.Forexample,thevaluereturnedforanarrayofintegersiscalculatedas2+8192,or8194.Ifanobjecthasadefaultproperty,VarType(object)returnsthetypeofitsdefaultproperty.
ThefollowingexampleusestheVarTypefunctiontodeterminethesubtypeofavariable.
DimMyCheckMyCheck=VarType(300)'Returns2.MyCheck=VarType(#10/19/62#)'Returns7.MyCheck=VarType("VBScript")'Returns8.
Microsoft®VisualBasic®ScriptingEdition
VBScriptConstants
LanguageReferenceVersion2
SeeAlso
AnumberofusefulconstantsyoucanuseinyourcodearebuiltintoVBScript.Constantsprovideaconvenientwaytousespecificvalueswithoutactuallyhavingtorememberthevalueitself.Usingconstantsalsomakesyourcodemoremaintainableshouldthevalueofanyconstanteverchange.BecausetheseconstantsarealreadydefinedinVBScript,youdon'tneedtoexplicitlydeclaretheminyourcode.Simplyusetheminplaceofthevaluestheyrepresent.
HerearethevariouscategoriesofconstantsprovidedinVBScriptandabriefdescriptionofeach:
ColorConstantsDefineseightbasiccolorsthatcanbeusedinscripting.
DateandTimeConstantsDefinesdateandtimeconstantsusedbyvariousdateandtimefunctions.
DateFormatConstantsDefinesconstantsusedtoformatdatesandtimes.
MiscellaneousConstantsDefinesconstantsthatdon'tconvenientlyfitintoanyothercategory.
MsgBoxConstantsDefinesconstantsusedintheMsgBoxfunctiontodescribebuttonvisibility,labeling,behavior,andreturnvalues.
StringConstantsDefinesavarietyofnon-printablecharactersusedinstringmanipulation.
TristateConstantsDefinesconstantsusedwithfunctionsthatformatnumbers.
VarTypeConstantsDefinesthevariousVariantsubtypes.
Microsoft®VisualBasic®ScriptingEdition
WeekdayFunctionLanguageReference
Version1
SeeAlso
Description
Returnsawholenumberrepresentingthedayoftheweek.
Syntax
Weekday(date,[firstdayofweek])
TheWeekdayfunctionsyntaxhasthesearguments:
Part Description
date Anyexpressionthatcanrepresentadate.IfdatecontainsNull,Nullisreturned.
firstdayofweek Aconstantthatspecifiesthefirstdayoftheweek.Ifomitted,vbSundayisassumed.
Settings
Thefirstdayofweekargumenthasthesesettings:
Constant Value Description
vbUseSystem 0 UseNationalLanguageSupport(NLS)APIsetting.
vbSunday 1 SundayvbMonday 2 MondayvbTuesday 3 TuesdayvbWednesday 4 WednesdayvbThursday 5 ThursdayvbFriday 6 FridayvbSaturday 7 Saturday
ReturnValues
TheWeekdayfunctioncanreturnanyofthesevalues:
Constant Value DescriptionvbSunday 1 SundayvbMonday 2 MondayvbTuesday 3 TuesdayvbWednesday 4 WednesdayvbThursday 5 ThursdayvbFriday 6 FridayvbSaturday 7 Saturday
Remarks
ThefollowingexampleusestheWeekdayfunctiontoobtainthedayoftheweekfromaspecifieddate:
DimMyDate,MyWeekDayMyDate=#October19,1962#'Assignadate.MyWeekDay=Weekday(MyDate)'MyWeekDaycontains6because'MyDaterepresentsaFriday.
Microsoft®VisualBasic®ScriptingEdition
While...WendStatement
LanguageReferenceVersion1
SeeAlso
Description
ExecutesaseriesofstatementsaslongasagivenconditionisTrue.
Syntax
WhileconditionVersion[statements]Wend
TheWhile...Wendstatementsyntaxhastheseparts:
Part Description
conditionNumericorstringexpressionthatevaluatestoTrueorFalse.IfconditionisNull,conditionistreatedasFalse.
statements OneormorestatementsexecutedwhileconditionisTrue.
Remarks
IfconditionisTrue,allstatementsinstatementsareexecuteduntiltheWendstatementisencountered.ControlthenreturnstotheWhilestatementandconditionisagainchecked.IfconditionisstillTrue,theprocessisrepeated.IfitisnotTrue,executionresumeswiththestatementfollowingtheWendstatement.
While...Wendloopscanbenestedtoanylevel.EachWendmatchesthemostrecentWhile.
TipTheDo...Loopstatementprovidesamorestructuredandflexiblewaytoperformlooping.
ThefollowingexampleillustratesuseoftheWhile...Wendstatement:
DimCounterCounter=0'Initializevariable.WhileCounter<20'TestvalueofCounter.Counter=Counter+1'IncrementCounter.AlertCounterWend'EndWhileloopwhenCounter>19.
Microsoft®VisualBasic®ScriptingEditionWithStatement
LanguageReferenceVersion5
SeeAlso
Description
Executesaseriesofstatementsonasingleobject.
Syntax
WithobjectstatementsEndWith
TheWithstatementsyntaxhastheseparts:
Part Descriptionobject Required.Nameofanobjectorafunctionthatreturnsanobject.
statements Required.Oneormorestatementstobeexecutedonobject.
Remarks
TheWithstatementallowsyoutoperformaseriesofstatementsonaspecifiedobjectwithoutrequalifyingthenameoftheobject.Forexample,tochangeanumberofdifferentpropertiesonasingleobject,placethepropertyassignmentstatementswithintheWithcontrolstructure,referringtotheobjectonceinsteadofreferringtoitwitheachpropertyassignment.ThefollowingexampleillustratesuseoftheWithstatementtoassignvaluestoseveralpropertiesofthesameobject.
WithMyLabel.Height=2000.Width=2000.Caption="ThisisMyLabel"EndWith
WhilepropertymanipulationisanimportantaspectofWithfunctionality,itisnottheonlyuse.AnylegalcodecanbeusedwithinaWithblock.
NoteOnceaWithblockisentered,objectcan'tbechanged.Asaresult,youcan'tuseasingleWithstatementtoaffectanumberofdifferentobjects.
YoucannestWithstatementsbyplacingoneWithblockwithinanother.However,becausemembersofouterWithblocksaremaskedwithintheinnerWithblocks,youmustprovideafullyqualifiedobjectreferenceinaninnerWithblocktoanymemberofanobjectinanouterWithblock.
ImportantDonotjumpintooroutofWithblocks.IfstatementsinaWithblockareexecuted,buteithertheWithorEndWithstatementisnotexecuted,youmaygeterrorsorunpredictablebehavior.
Microsoft®VisualBasic®ScriptingEditionXorOperator
LanguageReferenceVersion1
SeeAlso
Description
Performsalogicalexclusionontwoexpressions.
Syntax
result=expression1Xorexpression2
TheXoroperatorsyntaxhastheseparts:
Part Descriptionresult Anynumericvariable.expression1 Anyexpression.expression2 Anyexpression.
Remarks
Ifone,andonlyone,oftheexpressionsevaluatestoTrue,resultisTrue.However,ifeitherexpressionisNull,resultisalsoNull.WhenneitherexpressionisNull,resultisdeterminedaccordingtothefollowingtable:
Ifexpression1is Andexpression2is ThenresultisTrue True FalseTrue False TrueFalse True TrueFalse False False
TheXoroperatoralsoperformsabitwisecomparisonofidentically
positionedbitsintwonumericexpressionsandsetsthecorrespondingbitinresultaccordingtothefollowingtable:
Ifbitinexpression1is Andbitinexpression2is Thenresultis
0 0 00 1 11 0 11 1 0
Microsoft®VisualBasic®ScriptingEditionYearFunction
LanguageReferenceVersion1
SeeAlso
Description
Returnsawholenumberrepresentingtheyear.
Syntax
Year(date)
Thedateargumentisanyexpressionthatcanrepresentadate.IfdatecontainsNull,Nullisreturned.
Remarks
ThefollowingexampleusestheYearfunctiontoobtaintheyearfromaspecifieddate:
DimMyDate,MyYearMyDate=#October19,1962#'Assignadate.MyYear=Year(MyDate)'MyYearcontains1962.
Microsoft®VisualBasic®ScriptingEditionColorConstants
LanguageReferenceVersion2
SeeAlso
SincetheseconstantsarebuiltintoVBScript,youdon'thavetodefinethembeforeusingthem.Usethemanywhereinyourcodetorepresentthevaluesshownforeach.
Constant Value DescriptionvbBlack &h00; BlackvbRed &hFF; RedvbGreen &hFF00; GreenvbYellow &hFFFF; YellowvbBlue &hFF0000; BluevbMagenta &hFF00FF; MagentavbCyan &hFFFF00; CyanvbWhite &hFFFFFF; White
Microsoft®VisualBasic®ScriptingEditionTristateConstants
LanguageReferenceVersion2
SeeAlso
SincetheseconstantsarebuiltintoVBScript,youdon'thavetodefinethembeforeusingthem.Usethemanywhereinyourcodetorepresentthevaluesshownforeach.
Constant Value Description
vbUseDefault -2 Usedefaultfromcomputer'sregionalsettings.
vbTrue -1 TruevbFalse 0 False
Microsoft®VisualBasic®ScriptingEdition
VBScriptRun-timeErrors
LanguageReferenceVersion1
VBScriptSyntaxErrors
ErrorNumber Description5 Invalidprocedurecallorargument6 Overflow7 Outofmemory9 Subscriptoutofrange10 Thisarrayisfixedortemporarilylocked11 Divisionbyzero13 Typemismatch14 Outofstringspace17 Can'tperformrequestedoperation28 Outofstackspace35 SuborFunctionnotdefined48 ErrorinloadingDLL51 Internalerror52 Badfilenameornumber53 Filenotfound54 Badfilemode55 Filealreadyopen57 DeviceI/Oerror58 Filealreadyexists61 Diskfull62 Inputpastendoffile67 Toomanyfiles68 Deviceunavailable70 Permissiondenied71 Disknotready74 Can'trenamewithdifferentdrive75 Path/Fileaccesserror76 Pathnotfound91 Objectvariablenotset
92 Forloopnotinitialized94 InvaliduseofNull322 Can'tcreatenecessarytemporaryfile424 Objectrequired429 ActiveXcomponentcan'tcreateobject430 Classdoesn'tsupportAutomation432 FilenameorclassnamenotfoundduringAutomationoperation438 Objectdoesn'tsupportthispropertyormethod440 Automationerror445 Objectdoesn'tsupportthisaction446 Objectdoesn'tsupportnamedarguments447 Objectdoesn'tsupportcurrentlocalesetting448 Namedargumentnotfound449 Argumentnotoptional450 Wrongnumberofargumentsorinvalidpropertyassignment451 Objectnotacollection453 SpecifiedDLLfunctionnotfound455 Coderesourcelockerror458 VariableusesanAutomationtypenotsupportedinVBScript462 Theremoteservermachinedoesnotexistorisunavailable481 Invalidpicture500 Variableisundefined501 Illegalassignment502 Objectnotsafeforscripting503 Objectnotsafeforinitializing504 Objectnotsafeforcreating505 Invalidorunqualifiedreference506 Classnotdefined507 Anexceptionoccurred5016 RegularExpressionobjectexpected5017 Syntaxerrorinregularexpression5018 Unexpectedquantifier5019 Expected']'inregularexpression5020 Expected')'inregularexpression5021 Invalidrangeincharacterset32811 Elementnotfound
Microsoft®VisualBasic®ScriptingEdition
VBScriptSyntaxErrors
LanguageReferenceVersion1
VBScriptRun-timeErrors
ErrorNumber Description1001 Outofmemory1002 Syntaxerror1003 Expected':'1005 Expected'('1006 Expected')'1007 Expected']'1010 Expectedidentifier1011 Expected'='1012 Expected'If'1013 Expected'To'1014 Expected'End'1015 Expected'Function'1016 Expected'Sub'1017 Expected'Then'1018 Expected'Wend'1019 Expected'Loop'1020 Expected'Next'1021 Expected'Case'1022 Expected'Select'1023 Expectedexpression1024 Expectedstatement1025 Expectedendofstatement1026 Expectedintegerconstant1027 Expected'While'or'Until'1028 Expected'While','Until'orendofstatement1029 Expected'With'1030 Identifiertoolong1031 Invalidnumber1032 Invalidcharacter
1033 Unterminatedstringconstant1034 Unterminatedcomment1037 Invaliduseof'Me'keyword1038 'loop'without'do'1039 Invalid'exit'statement1040 Invalid'for'loopcontrolvariable1041 Nameredefined1042 Mustbefirststatementontheline1043 Cannotassigntonon-ByValargument1044 CannotuseparentheseswhencallingaSub1045 Expectedliteralconstant1046 Expected'In'1047 Expected'Class'1048 MustbedefinedinsideaClass1049 ExpectedLetorSetorGetinpropertydeclaration1050 Expected'Property'
1051 Numberofargumentsmustbeconsistentacrosspropertiesspecification
1052 Cannothavemultipledefaultproperty/methodinaClass1053 Classinitializeorterminatedonothavearguments1054 Propertysetorletmusthaveatleastoneargument1055 Unexpected'Next'1056 'Default'canbespecifiedonlyon'Property'or'Function'or'Sub'1057 'Default'specificationmustalsospecify'Public'")1058 'Default'specificationcanonlybeonPropertyGet
<operator">operator"><=operator">=operator">operator"><operator;lessthanoperator;>operator;greaterthanoperator;<=operator;lessthanorequaltooperator;>=operator;greaterthanorequaltooperator;=operator;equaloperator;operator;notequaloperator;stringcomparison;Empty">Microsoft®VisualBasic®ScriptingEdition
ComparisonOperators
LanguageReferenceVersion1
SeeAlso
Description
Usedtocompareexpressions.
Syntax
result=expression1comparisonoperatorexpression2
result=object1Isobject2
Comparisonoperatorshavetheseparts:
Part Descriptionresult Anynumericvariable.expression Anyexpression.comparisonoperator Anycomparisonoperator.object Anyobjectname.
Remarks
TheIsoperatorhasspecificcomparisonfunctionalitythatdiffersfromtheoperatorsinthefollowingtable.ThefollowingtablecontainsalistofthecomparisonoperatorsandtheconditionsthatdeterminewhetherresultisTrue,False,orNull:
Operator Description Trueif Falseif Nullif
< Lessthanexpression1<expression2
expression1>=expression2
expression1orexpression2=Null
<= Lessthanorequalto
expression1<=expression2
expression1>expression2
expression1orexpression2=Null
> Greaterthan
expression1>expression2
expression1<=expression2
expression1orexpression2=Null
>=Greaterthanorequalto
expression1>=expression2
expression1<expression2
expression1orexpression2=Null
= Equaltoexpression1=expression2
expression1<>expression2
expression1orexpression2=Null
<> Notequaltoexpression1<>expression2
expression1=expression2
expression1orexpression2=Null
Whencomparingtwoexpressions,youmaynotbeabletoeasilydeterminewhethertheexpressionsarebeingcomparedasnumbersorasstrings.
Thefollowingtableshowshowexpressionsarecomparedorwhatresultsfromthecomparison,dependingontheunderlyingsubtype:
If ThenBothexpressionsarenumeric Performanumericcomparison.
Bothexpressionsarestrings Performastringcomparison.
Oneexpressionisnumericandtheotherisastring
Thenumericexpressionislessthanthestringexpression.
OneexpressionisEmptyandtheotherisnumeric
Performanumericcomparison,using0astheEmptyexpression.
OneexpressionisEmptyandtheotherisastring
Performastringcomparison,usingazero-lengthstring("")astheEmptyexpression.
BothexpressionsareEmpty Theexpressionsareequal.
Microsoft®VisualBasic®ScriptingEdition
VBScriptLanguageReference
VBScriptTutorialVersionInformation
FeatureInformation
AlphabeticKeywordList
Constants
Errors
Events
Functions
Methods
Objects
Operators
WelcometotheVBScriptLanguageReference
ThesehandyblocksofinformationwillhelpyouexplorethemanydifferentpartsoftheVisualBasicScriptinglanguage.
You'llfindallthepartsoftheVBScriptlanguagelistedalphabeticallyundertheAlphabeticKeywordList.Butifyouwanttoexaminejustonecategory,say,objects,eachlanguagecategoryhasitsown,morecompactsection.
How'sitwork?Clickononeoftheheadingstothelefttodisplayalistofitemscontainedinthatcategory.Fromthislist,selectthetopicthatyouwanttoview.Onceyou'veopenedthattopic,youcaneasilylinktootherrelatedsections.
So,goaheadandtakealook!Studysomestatements,mulloverthemethods,orfigureout
Properties
Statements
afewfunctions.You'llseejusthowversatiletheVBScriptlanguagecanbe!
©1999MicrosoftCorporation.Allrightsreserved.
Microsoft®VisualBasic®ScriptingEditionAddMethod(Dictionary)
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesto
Description
AddsakeyanditempairtoaDictionaryobject.
Syntax
object.Addkey,item
TheAddmethodhasthefollowingparts:
Part Descriptionobject Required.AlwaysthenameofaDictionaryobject.key Required.Thekeyassociatedwiththeitembeingadded.item Required.Theitemassociatedwiththekeybeingadded.
Remarks
Anerroroccursifthekeyalreadyexists.
ThefollowingexampleillustratestheuseoftheAddmethod:
Dimd'Createavariable.Setd=CreateObject("Scripting.Dictionary")d.Add"a","Athens"'Addsomekeysanditems.d.Add"b","Belgrade"d.Add"c","Cairo"
Microsoft®VisualBasic®ScriptingEditionAddMethod(Folders)
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
AddsanewFoldertoaFolderscollection.
Syntax
object.Add(folderName)
TheAddmethodhasthefollowingparts:
Part Descriptionobject Required.AlwaysthenameofaFolderscollection.
folderName Required.ThenameofthenewFolderbeingadded.
Remarks
ThefollowingexampleillustratestheuseoftheAddmethodtoaddanewfolder:
SubAddNewFolder(path,folderName)Dimfso,f,fc,nfSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFolder(path)Setfc=f.SubFoldersIffolderName<>""ThenSetnf=fc.Add(folderName)ElseSetnf=fc.Add("NewFolder")
EndIfEndSub
AnerroroccursiffolderNamealreadyexists.
Microsoft®VisualBasic®ScriptingEdition
AtEndOfLineProperty
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesto
Description
ReturnsTrueifthefilepointerimmediatelyprecedestheend-of-linemarkerinaTextStreamfile;Falseifitisnot.Read-only.
Syntax
object.AtEndOfLine
TheobjectisalwaysthenameofaTextStreamobject.
Remarks
TheAtEndOfLinepropertyappliesonlytoTextStreamfilesthatareopenforreading;otherwise,anerroroccurs.
ThefollowingcodeillustratestheuseoftheAtEndOfLineproperty:
FunctionReadEntireFile(filespec)ConstForReading=1Dimfso,theFile,retstringSetfso=CreateObject("Scripting.FileSystemObject")SettheFile=fso.OpenTextFile(filespec,ForReading,False)DoWhiletheFile.AtEndOfLine<>Trueretstring=theFile.Read(1)Loop
theFile.CloseReadEntireFile=retstringEndFunction
Microsoft®VisualBasic®ScriptingEdition
AtEndOfStreamProperty
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesto
Description
ReturnsTrueifthefilepointerisattheendofaTextStreamfile;Falseifitisnot.Read-only.
Syntax
object.AtEndOfStream
TheobjectisalwaysthenameofaTextStreamobject.
Remarks
TheAtEndOfStreampropertyappliesonlytoTextStreamfilesthatareopenforreading,otherwise,anerroroccurs.
ThefollowingcodeillustratestheuseoftheAtEndOfStreamproperty:
FunctionReadEntireFile(filespec)ConstForReading=1Dimfso,theFile,retstringSetfso=CreateObject("Scripting.FileSystemObject")SettheFile=fso.OpenTextFile(filespec,ForReading,False)DoWhiletheFile.AtEndOfStream<>Trueretstring=theFile.ReadLineLoop
theFile.CloseReadEntireFile=retstringEndFunction
Microsoft®VisualBasic®ScriptingEdition
AttributesProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Setsorreturnstheattributesoffilesorfolders.Read/writeorread-only,dependingontheattribute.
Syntax
object.Attributes[=newattributes]
TheAttributespropertyhastheseparts:
Part Description
object Required.AlwaysthenameofaFileorFolderobject.
newattributes Optional.Ifprovided,newattributesisthenewvaluefortheattributesofthespecifiedobject.
Settings
Thenewattributesargumentcanhaveanyofthefollowingvaluesoranylogicalcombinationofthefollowingvalues:
Constant Value DescriptionNormal 0 Normalfile.Noattributesareset.ReadOnly 1 Read-onlyfile.Attributeisread/write.Hidden 2 Hiddenfile.Attributeisread/write.System 4 Systemfile.Attributeisread/write.Directory 16 Folderordirectory.Attributeisread-only.
Archive 32 Filehaschangedsincelastbackup.Attributeisread/write.
Alias 1024 Linkorshortcut.Attributeisread-only.Compressed 2048 Compressedfile.Attributeisread-only.
Remarks
Attemptstochangeanyoftheread-onlyattributes(Alias,Compressed,orDirectory)areignored.
Whensettingattributes,itisgenerallyagoodideatofirstreadthecurrentattributes,thenchangetheindividualattributesasdesired,andfinallywritetheattributesback.
ThefollowingcodeillustratestheuseoftheAttributespropertywithafile:
FunctionToggleArchiveBit(filespec)Dimfso,fSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFile(filespec)Iff.attributesand32Thenf.attributes=f.attributes-32ToggleArchiveBit="Archivebitiscleared."Elsef.attributes=f.attributes+32ToggleArchiveBit="Archivebitisset."EndIfEndFunction
Microsoft®VisualBasic®ScriptingEdition
AvailableSpaceProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnstheamountofspaceavailabletoauseronthespecifieddriveornetworkshare.
Syntax
object.AvailableSpace
TheobjectisalwaysaDriveobject.
Remarks
ThevaluereturnedbytheAvailableSpacepropertyistypicallythesameasthatreturnedbytheFreeSpaceproperty.Differencesmayoccurbetweenthetwoforcomputersystemsthatsupportquotas.
ThefollowingcodeillustratestheuseoftheAvailableSpaceproperty:
FunctionShowAvailableSpace(drvPath)Dimfso,d,sSetfso=CreateObject("Scripting.FileSystemObject")Setd=fso.GetDrive(fso.GetDriveName(drvPath))s="Drive"&UCase(drvPath)&"-"s=s&d.VolumeName&"<BR>"s=s&"AvailableSpace:"&FormatNumber(d.AvailableSpace/1024,0)s=s&"Kbytes"ShowAvailableSpace=sEndFunction
Microsoft®VisualBasic®ScriptingEdition
BuildPathMethodScriptingRun-TimeReference
Version3
SeeAlsoAppliesTo
Description
Appendsanametoanexistingpath.
Syntax
object.BuildPath(path,name)
TheBuildPathmethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
pathRequired.Existingpathtowhichnameisappended.Pathcanbeabsoluteorrelativeandneednotspecifyanexistingfolder.
name Required.Namebeingappendedtotheexistingpath.
Remarks
TheBuildPathmethodinsertsanadditionalpathseparatorbetweentheexistingpathandthename,onlyifnecessary.
ThefollowingexampleillustratesuseoftheBuildPathmethod:
FunctionGetBuildPath(path)Dimfso,newpathSetfso=CreateObject("Scripting.FileSystemObject")newpath=fso.BuildPath(path,"SubFolder")GetBuildPath=newpath
EndFunction
Microsoft®VisualBasic®ScriptingEditionCloseMethod
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesto
Description
ClosesanopenTextStreamfile.
Syntax
object.Close
TheobjectisalwaysthenameofaTextStreamobject.
Remarks
ThefollowingexampleillustratesuseoftheClosemethodtocloseanopenTextStreamfile:
SubCreateAFileDimfso,MyFileSetfso=CreateObject("Scripting.FileSystemObject")SetMyFile=fso.CreateTextFile("c:\testfile.txt",True)MyFile.WriteLine("Thisisatest.")MyFile.CloseEndSub
Microsoft®VisualBasic®ScriptingEditionColumnProperty
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesto
Description
Read-onlypropertythatreturnsthecolumnnumberofthecurrentcharacterpositioninaTextStreamfile.
Syntax
object.Column
TheobjectisalwaysthenameofaTextStreamobject.
Remarks
Afteranewlinecharacterhasbeenwritten,butbeforeanyothercharacteriswritten,Columnisequalto1.
ThefollowingexampleillustratesuseoftheColumnproperty:
FunctionGetColumnConstForReading=1,ForWriting=2Dimfso,f,mSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.OpenTextFile("c:\testfile.txt",ForWriting,True)f.Write"Helloworld!"f.CloseSetf=fso.OpenTextFile("c:\testfile.txt",ForReading)m=f.ReadLine
GetColumn=f.ColumnEndFunction
Microsoft®VisualBasic®ScriptingEdition
CompareModeProperty
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesto
Description
SetsandreturnsthecomparisonmodeforcomparingstringkeysinaDictionaryobject.
Syntax
object.CompareMode[=compare]
TheCompareModepropertyhasthefollowingparts:
Part Descriptionobject Required.AlwaysthenameofaDictionaryobject.
compareOptional.Ifprovided,compareisavaluerepresentingthecomparisonmodeusedbyfunctionssuchasStrComp.
Settings
Thecompareargumenthasthefollowingsettings:
Constant Value Description
vbBinaryCompare 0Performabinarycomparison.
vbTextCompare 1Performatextualcomparison.
Remarks
Valuesgreaterthan2canbeusedtorefertocomparisonsusingspecific
LocaleIDs(LCID).AnerroroccursifyoutrytochangethecomparisonmodeofaDictionaryobjectthatalreadycontainsdata.
TheCompareModepropertyusesthesamevaluesasthecompareargumentfortheStrCompfunction.
ThefollowingexampleillustratesuseoftheCompareModeproperty:
DimdSetd=CreateObject("Scripting.Dictionary")d.CompareMode=vbTextCompared.Add"a","Athens"'Addsomekeysanditems.d.Add"b","Belgrade"d.Add"c","Cairo"d.Add"B","Baltimore"'Addmethodfailsonthislinebecausethe'letterbalreadyexistsintheDictionary.
Microsoft®VisualBasic®ScriptingEditionCopyMethod
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Copiesaspecifiedfileorfolderfromonelocationtoanother.
Syntax
object.Copydestination[,overwrite]
TheCopymethodsyntaxhastheseparts:
Part Description
object Required.AlwaysthenameofaFileorFolderobject.
destination Required.Destinationwherethefileorfolderistobecopied.Wildcardcharactersarenotallowed.
overwriteOptional.BooleanvaluethatisTrue(default)ifexistingfilesorfoldersaretobeoverwritten;Falseiftheyarenot.
Remarks
TheresultsoftheCopymethodonaFileorFolderareidenticaltooperationsperformedusingFileSystemObject.CopyFileorFileSystemObject.CopyFolderwherethefileorfolderreferredtobyobjectispassedasanargument.Youshouldnote,however,thatthealternativemethodsarecapableofcopyingmultiplefilesorfolders.
ThefollowingexampleillustratesuseoftheCopymethod:
Dimfso,MyFile
Setfso=CreateObject("Scripting.FileSystemObject")SetMyFile=fso.CreateTextFile("c:\testfile.txt",True)MyFile.WriteLine("Thisisatest.")MyFile.CloseSetMyFile=fso.GetFile("c:\testfile.txt")MyFile.Copy("c:\windows\desktop\test2.txt")
Microsoft®VisualBasic®ScriptingEdition
CopyFileMethodScriptingRun-TimeReference
Version3
SeeAlsoAppliesTo
Description
Copiesoneormorefilesfromonelocationtoanother.
Syntax
object.CopyFilesource,destination[,overwrite]
TheCopyFilemethodsyntaxhastheseparts:
Part Description
object Required.TheobjectisalwaysthenameofaFileSystemObject.
sourceRequired.Characterstringfilespecification,whichcanincludewildcardcharacters,foroneormorefilestobecopied.
destinationRequired.Characterstringdestinationwherethefileorfilesfromsourcearetobecopied.Wildcardcharactersarenotallowed.
overwrite
Optional.Booleanvaluethatindicatesifexistingfilesaretobeoverwritten.IfTrue,filesareoverwritten;ifFalse,theyarenot.ThedefaultisTrue.NotethatCopyFilewillfailifdestinationhastheread-onlyattributeset,regardlessofthevalueofoverwrite.
Remarks
Wildcardcharacterscanonlybeusedinthelastpathcomponentofthesourceargument.Forexample,youcanuse:
FileSystemObject.CopyFile"c:\mydocuments\letters\*.doc","c:\tempfolder\"
Butyoucan'tuse:
FileSystemObject.CopyFile"c:\mydocuments\*\R1???97.xls","c:\tempfolder"
Ifsourcecontainswildcardcharactersordestinationendswithapathseparator(\),itisassumedthatdestinationisanexistingfolderinwhichtocopymatchingfiles.Otherwise,destinationisassumedtobethenameofafiletocreate.Ineithercase,threethingscanhappenwhenanindividualfileiscopied.
Ifdestinationdoesnotexist,sourcegetscopied.Thisistheusualcase.
Ifdestinationisanexistingfile,anerroroccursifoverwriteisFalse.Otherwise,anattemptismadetocopysourceovertheexistingfile.
Ifdestinationisadirectory,anerroroccurs.
Anerroralsooccursifasourceusingwildcardcharactersdoesn'tmatchanyfiles.TheCopyFilemethodstopsonthefirsterroritencounters.Noattemptismadetorollbackorundoanychangesmadebeforeanerroroccurs.
Microsoft®VisualBasic®ScriptingEdition
CopyFolderMethod
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Recursivelycopiesafolderfromonelocationtoanother.
Syntax
object.CopyFoldersource,destination[,overwrite]
TheCopyFoldermethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
sourceRequired.Characterstringfolderspecification,whichcanincludewildcardcharacters,foroneormorefolderstobecopied.
destinationRequired.Characterstringdestinationwherethefolderandsubfoldersfromsourcearetobecopied.Wildcardcharactersarenotallowed.
overwrite
Optional.Booleanvaluethatindicatesifexistingfoldersaretobeoverwritten.IfTrue,filesareoverwritten;ifFalse,theyarenot.ThedefaultisTrue.
Remarks
Wildcardcharacterscanonlybeusedinthelastpathcomponentofthesourceargument.Forexample,youcanuse:
FileSystemObject.CopyFolder"c:\mydocuments\letters\*","c:\tempfolder\"
Butyoucan'tuse:
FileSystemObject.CopyFolder"c:\mydocuments\*\*","c:\tempfolder\"
Ifsourcecontainswildcardcharactersordestinationendswithapathseparator(\),itisassumedthatdestinationisanexistingfolderinwhichtocopymatchingfoldersandsubfolders.Otherwise,destinationisassumedtobethenameofafoldertocreate.Ineithercase,fourthingscanhappenwhenanindividualfolderiscopied.
Ifdestinationdoesnotexist,thesourcefolderandallitscontentsgetscopied.Thisistheusualcase.
Ifdestinationisanexistingfile,anerroroccurs.
Ifdestinationisadirectory,anattemptismadetocopythefolderandallitscontents.Ifafilecontainedinsourcealreadyexistsindestination,anerroroccursifoverwriteisFalse.Otherwise,itwillattempttocopythefileovertheexistingfile.
Ifdestinationisaread-onlydirectory,anerroroccursifanattemptismadetocopyanexistingread-onlyfileintothatdirectoryandoverwriteisFalse.
Anerroralsooccursifasourceusingwildcardcharactersdoesn'tmatchanyfolders.
TheCopyFoldermethodstopsonthefirsterroritencounters.Noattemptismadetorollbackanychangesmadebeforeanerroroccurs.
Microsoft®VisualBasic®ScriptingEditionCountProperty
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesTo
Description
ReturnsthenumberofitemsinacollectionorDictionaryobject.Read-only.
Syntax
object.Count
TheobjectisalwaysthenameofoneoftheitemsintheAppliesTolist.
Remarks
ThefollowingcodeillustratesuseoftheCountproperty:
FunctionShowKeysDima,d,i,s'Createsomevariables.Setd=CreateObject("Scripting.Dictionary")d.Add"a","Athens"'Addsomekeysanditems.d.Add"b","Belgrade"d.Add"c","Cairo"a=d.Keys'Getthekeys.Fori=0Tod.Count-1'Iteratethearray.s=s&a(i)&"<BR>"'Createreturnstring.NextShowKeys=sEndFunction
Microsoft®VisualBasic®ScriptingEdition
CreateFolderMethod
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Createsafolder.
Syntax
object.CreateFolder(foldername)
TheCreateFoldermethodhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
foldername Required.Stringexpressionthatidentifiesthefoldertocreate.
Remarks
Anerroroccursifthespecifiedfolderalreadyexists.
ThefollowingexampleillustratesuseoftheCreateFoldermethod:
FunctionCreateFolderDemoDimfso,fSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.CreateFolder("c:\NewFolder")CreateFolderDemo=f.PathEndFunction
Microsoft®VisualBasic®ScriptingEdition
CreateTextFileMethod
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesto
Description
CreatesaspecifiedfilenameandreturnsaTextStreamobjectthatcanbeusedtoreadfromorwritetothefile.
Syntax
object.CreateTextFile(filename[,overwrite[,unicode]])
TheCreateTextFilemethodhastheseparts:
Part Description
object Required.AlwaysthenameofaFileSystemObjectorFolderobject.
filename Required.Stringexpressionthatidentifiesthefiletocreate.
overwrite
Optional.Booleanvaluethatindicatesifanexistingfilecanbeoverwritten.ThevalueisTrueifthefilecanbeoverwritten;Falseifitcan'tbeoverwritten.Ifomitted,existingfilesarenotoverwritten.
unicode
Optional.BooleanvaluethatindicateswhetherthefileiscreatedasaUnicodeorASCIIfile.ThevalueisTrueifthefileiscreatedasaUnicodefile;Falseifit'screatedasanASCIIfile.Ifomitted,anASCIIfileisassumed.
Remarks
ThefollowingcodeillustrateshowtousetheCreateTextFilemethodto
createandopenatextfile:
SubCreateAfileDimfso,MyFileSetfso=CreateObject("Scripting.FileSystemObject")SetMyFile=fso.CreateTextFile("c:\testfile.txt",True)MyFile.WriteLine("Thisisatest.")MyFile.CloseEndSub
IftheoverwriteargumentisFalse,orisnotprovided,forafilenamethatalreadyexists,anerroroccurs.
Microsoft®VisualBasic®ScriptingEdition
DateCreatedProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnsthedateandtimethatthespecifiedfileorfolderwascreated.Read-only.
Syntax
object.DateCreated
TheobjectisalwaysaFileorFolderobject.
Remarks
ThefollowingcodeillustratestheuseoftheDateCreatedpropertywithafile:
FunctionShowFileInfo(filespec)Dimfso,fSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFile(filespec)ShowFileInfo="Created:"&f.DateCreatedEndFunction
Microsoft®VisualBasic®ScriptingEdition
DateLastAccessedProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnsthedateandtimethatthespecifiedfileorfolderwaslastaccessed.Read-only.
Syntax
object.DateLastAccessed
TheobjectisalwaysaFileorFolderobject.
Remarks
ThefollowingcodeillustratestheuseoftheDateLastAccessedpropertywithafile:
FunctionShowFileAccessInfo(filespec)Dimfso,f,sSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFile(filespec)s=UCase(filespec)&"<BR>"s=s&"Created:"&f.DateCreated&"<BR>"s=s&"LastAccessed:"&f.DateLastAccessed&"<BR>"s=s&"LastModified:"&f.DateLastModifiedShowFileAccessInfo=sEndFunction
ImportantThismethoddependsontheunderlyingoperatingsystemforitsbehavior.
Iftheoperatingsystemdoesnotsupportprovidingtimeinformation,nonewillbereturned.
Microsoft®VisualBasic®ScriptingEdition
DateLastModifiedProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnsthedateandtimethatthespecifiedfileorfolderwaslastmodified.Read-only.
Syntax
object.DateLastModified
TheobjectisalwaysaFileorFolderobject.
Remarks
ThefollowingcodeillustratestheuseoftheDateLastModifiedpropertywithafile:
FunctionShowFileAccessInfo(filespec)Dimfso,f,sSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFile(filespec)s=UCase(filespec)&"<BR>"s=s&"Created:"&f.DateCreated&"<BR>"s=s&"LastAccessed:"&f.DateLastAccessed&"<BR>"s=s&"LastModified:"&f.DateLastModifiedShowFileAccessInfo=sEndFunction
Microsoft®VisualBasic®ScriptingEditionDeleteMethod
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Deletesaspecifiedfileorfolder.
Syntax
object.Deleteforce
TheDeletemethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileorFolderobject.
forceOptional.BooleanvaluethatisTrueiffilesorfolderswiththeread-onlyattributesetaretobedeleted;False(default)iftheyarenot.
Remarks
Anerroroccursifthespecifiedfileorfolderdoesnotexist.TheDeletemethoddoesnotdistinguishbetweenfoldersthathavecontentsandthosethatdonot.Thespecifiedfolderisdeletedregardlessofwhetherornotithascontents.
TheresultsoftheDeletemethodonaFileorFolderareidenticaltooperationsperformedusingFileSystemObject.DeleteFileorFileSystemObject.DeleteFolder.
ThefollowingexampleillustratesuseoftheDeletemethod:
Dimfso,MyFileSetfso=CreateObject("Scripting.FileSystemObject")
SetMyFile=fso.CreateTextFile("c:\testfile.txt",True)MyFile.WriteLine("Thisisatest.")MyFile.CloseSetMyFile=fso.GetFile("c:\testfile.txt")MyFile.Delete
Microsoft®VisualBasic®ScriptingEdition
DeleteFileMethodScriptingRun-TimeReference
Version3
SeeAlsoAppliesTo
Description
Deletesaspecifiedfile.
Syntax
object.DeleteFilefilespec[,force]
TheDeleteFilemethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
filespecRequired.Thenameofthefiletodelete.Thefilespeccancontainwildcardcharactersinthelastpathcomponent.
forceOptional.BooleanvaluethatisTrueiffileswiththeread-onlyattributesetaretobedeleted;False(default)iftheyarenot.
Remarks
Anerroroccursifnomatchingfilesarefound.TheDeleteFilemethodstopsonthefirsterroritencounters.Noattemptismadetorollbackorundoanychangesthatweremadebeforeanerroroccurred.
ThefollowingexampleillustratesuseoftheDeleteFilemethod:
SubDeleteAFile(filespec)DimfsoSetfso=CreateObject("Scripting.FileSystemObject")
fso.DeleteFile(filespec)EndSub
Microsoft®VisualBasic®ScriptingEdition
DeleteFolderMethod
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Deletesaspecifiedfolderanditscontents.
Syntax
object.DeleteFolderfolderspec[,force]
TheDeleteFoldermethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
folderspecRequired.Thenameofthefoldertodelete.Thefolderspeccancontainwildcardcharactersinthelastpathcomponent.
forceOptional.BooleanvaluethatisTrueiffolderswiththeread-onlyattributesetaretobedeleted;False(default)iftheyarenot.
Remarks
TheDeleteFoldermethoddoesnotdistinguishbetweenfoldersthathavecontentsandthosethatdonot.Thespecifiedfolderisdeletedregardlessofwhetherornotithascontents.
Anerroroccursifnomatchingfoldersarefound.TheDeleteFoldermethodstopsonthefirsterroritencounters.Noattemptismadetorollbackorundoanychangesthatweremadebeforeanerroroccurred.
ThefollowingexampleillustratesuseoftheDeleteFoldermethod:
SubDeleteAFolder(filespec)DimfsoSetfso=CreateObject("Scripting.FileSystemObject")fso.DeleteFolder(filespec)EndSub
Microsoft®VisualBasic®ScriptingEdition
DictionaryObjectScriptingRun-TimeReference
Version2
SeeAlsoPropertiesMethods
Description
Objectthatstoresdatakey,itempairs.
Remarks
ADictionaryobjectistheequivalentofaPERLassociativearray.Items,whichcanbeanyformofdata,arestoredinthearray.Eachitemisassociatedwithauniquekey.Thekeyisusedtoretrieveanindividualitemandisusuallyaintegerorastring,butcanbeanythingexceptanarray.
ThefollowingcodeillustrateshowtocreateaDictionaryobject:
Dimd'Createavariable.Setd=CreateObject("Scripting.Dictionary")d.Add"a","Athens"'Addsomekeysanditems.d.Add"b","Belgrade"d.Add"c","Cairo"...
Microsoft®VisualBasic®ScriptingEditionDriveObject
ScriptingRun-TimeReferenceVersion3
SeeAlsoPropertiesMethods
Description
Providesaccesstothepropertiesofaparticulardiskdriveornetworkshare.
Remarks
ThefollowingcodeillustratestheuseoftheDriveobjecttoaccessdriveproperties:
FunctionShowFreeSpace(drvPath)Dimfso,d,sSetfso=CreateObject("Scripting.FileSystemObject")Setd=fso.GetDrive(fso.GetDriveName(drvPath))s="Drive"&UCase(drvPath)&"-"s=s&d.VolumeName&"<BR>"s=s&"FreeSpace:"&FormatNumber(d.FreeSpace/1024,0)s=s&"Kbytes"ShowFreeSpace=sEndFunction
Microsoft®VisualBasic®ScriptingEditionDriveProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnsthedriveletterofthedriveonwhichthespecifiedfileorfolderresides.Read-only.
Syntax
object.Drive
TheobjectisalwaysaFileorFolderobject.
Remarks
ThefollowingcodeillustratestheuseoftheDriveproperty:
FunctionShowFileAccessInfo(filespec)Dimfso,f,sSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFile(filespec)s=f.Name&"onDrive"&UCase(f.Drive)&"<BR>"s=s&"Created:"&f.DateCreated&"<BR>"s=s&"LastAccessed:"&f.DateLastAccessed&"<BR>"s=s&"LastModified:"&f.DateLastModifiedShowFileAccessInfo=sEndFunction
Microsoft®VisualBasic®ScriptingEdition
DriveExistsMethod
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
ReturnsTrueifthespecifieddriveexists;Falseifitdoesnot.
Syntax
object.DriveExists(drivespec)
TheDriveExistsmethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
drivespec Required.Adriveletteroracompletepathspecification.
Remarks
Fordriveswithremovablemedia,theDriveExistsmethodreturnsTrueeveniftherearenomediapresent.UsetheIsReadypropertyoftheDriveobjecttodetermineifadriveisready.
ThefollowingexampleillustratesuseoftheDriveExistsmethod:
FunctionReportDriveStatus(drv)Dimfso,msgSetfso=CreateObject("Scripting.FileSystemObject")Iffso.DriveExists(drv)Thenmsg=("Drive"&UCase(drv)&"exists.")Else
msg=("Drive"&UCase(drv)&"doesn'texist.")EndIfReportDriveStatus=msgEndFunction
Microsoft®VisualBasic®ScriptingEdition
DriveLetterProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnsthedriveletterofaphysicallocaldriveoranetworkshare.Read-only.
Syntax
object.DriveLetter
TheobjectisalwaysaDriveobject.
Remarks
TheDriveLetterpropertyreturnsazero-lengthstring("")ifthespecifieddriveisnotassociatedwithadriveletter,forexample,anetworksharethathasnotbeenmappedtoadriveletter.
ThefollowingcodeillustratestheuseoftheDriveLetterproperty:
FunctionShowDriveLetter(drvPath)Dimfso,d,sSetfso=CreateObject("Scripting.FileSystemObject")Setd=fso.GetDrive(fso.GetDriveName(drvPath))s="Drive"&d.DriveLetter&":-"s=s&d.VolumeName&"<BR>"s=s&"FreeSpace:"&FormatNumber(d.FreeSpace/1024,0)s=s&"Kbytes"ShowDriveLetter=sEndFunction
Microsoft®VisualBasic®ScriptingEdition
DrivesCollectionScriptingRun-TimeReference
Version3
SeeAlsoPropertiesMethods
Description
Read-onlycollectionofallavailabledrives.
Remarks
Removable-mediadrivesneednothavemediainsertedforthemtoappearintheDrivescollection.
ThefollowingcodeillustrateshowtogettheDrivescollectionanditeratethecollectionusingtheForEach...Nextstatement:
FunctionShowDriveListDimfso,d,dc,s,nSetfso=CreateObject("Scripting.FileSystemObject")Setdc=fso.DrivesForEachdindcn=""s=s&d.DriveLetter&"-"Ifd.DriveType=RemoteThenn=d.ShareNameElseIfd.IsReadyThenn=d.VolumeNameEndIfs=s&n&"<BR>"NextShowDriveList=sEndFunction
Microsoft®VisualBasic®ScriptingEditionDrivesProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
ReturnsaDrivescollectionconsistingofallDriveobjectsavailableonthelocalmachine.
Syntax
object.Drives
TheobjectisalwaysaFileSystemObject.
Remarks
Removable-mediadrivesneednothavemediainsertedforthemtoappearintheDrivescollection.
YoucaniteratethemembersoftheDrivescollectionusingaForEach...Nextconstructasillustratedinthefollowingcode:
FunctionShowDriveListDimfso,d,dc,s,nSetfso=CreateObject("Scripting.FileSystemObject")Setdc=fso.DrivesForEachdindcn=""s=s&d.DriveLetter&"-"Ifd.DriveType=3Thenn=d.ShareNameElseIfd.IsReadyThenn=d.VolumeName
EndIfs=s&n&"<BR>"NextShowDriveList=sEndFunction
Microsoft®VisualBasic®ScriptingEdition
DriveTypeConstants
ScriptingRun-TimeReferenceVersion3
SeeAlso
Theseconstantsareonlyavailablewhenyourprojecthasanexplicitreferencetotheappropriatetypelibrarycontainingtheseconstantdefinitions.ForVBScript,youmustexplicitlydeclaretheseconstantsinyourcode.
Constant Value DescriptionUnknown 0 Drivetypecan'tbedetermined.
Removable 1Drivehasremovablemedia.Thisincludesallfloppydrivesandmanyothervarietiesofstoragedevices.
Fixed 2Drivehasfixed(nonremovable)media.Thisincludesallharddrives,includingharddrivesthatareremovable.
Remote 3 Networkdrives.Thisincludesdrivessharedanywhereonanetwork.
CDROM 4DriveisaCD-ROM.Nodistinctionismadebetweenread-onlyandread/writeCD-ROMdrives.
RAMDisk 5DriveisablockofRandomAccessMemory(RAM)onthelocalcomputerthatbehaveslikeadiskdrive.
Microsoft®VisualBasic®ScriptingEdition
DriveTypeProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnsavalueindicatingthetypeofaspecifieddrive.
Syntax
object.DriveType
TheobjectisalwaysaDriveobject.
Remarks
ThefollowingcodeillustratestheuseoftheDriveTypeproperty:
FunctionShowDriveType(drvpath)Dimfso,d,tSetfso=CreateObject("Scripting.FileSystemObject")Setd=fso.GetDrive(drvpath)SelectCased.DriveTypeCase0:t="Unknown"Case1:t="Removable"Case2:t="Fixed"Case3:t="Network"Case4:t="CD-ROM"Case5:t="RAMDisk"EndSelectShowDriveType="Drive"&d.DriveLetter&":-"&tEndFunction
Microsoft®VisualBasic®ScriptingEditionExistsMethod
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesto
Description
ReturnsTrueifaspecifiedkeyexistsintheDictionaryobject,Falseifitdoesnot.
Syntax
object.Exists(key)
TheExistsmethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaDictionaryobject.
key Required.KeyvaluebeingsearchedforintheDictionaryobject.
Remarks
ThefollowingexampleillustratesuseoftheExistsmethod:
FunctionKeyExistsDemoDimd,msg'Createsomevariables.Setd=CreateObject("Scripting.Dictionary")d.Add"a","Athens"'Addsomekeysanditems.d.Add"b","Belgrade"d.Add"c","Cairo"Ifd.Exists("c")Thenmsg="Specifiedkeyexists."Else
msg="Specifiedkeydoesn'texist."EndIfKeyExistsDemo=msgEndFunction
Microsoft®VisualBasic®ScriptingEditionFileAttributeConstants
ScriptingRun-TimeReferenceVersion3
SeeAlso
Theseconstantsareonlyavailablewhenyourprojecthasanexplicitreferencetotheappropriatetypelibrarycontainingtheseconstantdefinitions.ForVBScript,youmustexplicitlydeclaretheseconstantsinyourcode.
Constant Value DescriptionNormal 0 Normalfile.Noattributesareset.ReadOnly 1 Read-onlyfile.Hidden 2 Hiddenfile.System 4 Systemfile.Directory 16 Folderordirectory.Archive 32 Filehaschangedsincelastbackup.Alias 1024 Linkorshortcut.Compressed 2048 Compressedfile.
Microsoft®VisualBasic®ScriptingEditionFileInput/OutputConstants
ScriptingRun-TimeReferenceVersion2
SeeAlso
Theseconstantsareonlyavailablewhenyourprojecthasanexplicitreferencetotheappropriatetypelibrarycontainingtheseconstantdefinitions.ForVBScript,youmustexplicitlydeclaretheseconstantsinyourcode.
Constant Value Description
ForReading 1 Openafileforreadingonly.Youcan'twritetothisfile.
ForWriting 2Openafileforwriting.Ifafilewiththesamenameexists,itspreviouscontentsareoverwritten.
ForAppending 8 Openafileandwritetotheendofthefile.
Microsoft®VisualBasic®ScriptingEdition
FileExistsMethodScriptingRun-TimeReference
Version3
SeeAlsoAppliesTo
Description
ReturnsTrueifaspecifiedfileexists;Falseifitdoesnot.
Syntax
object.FileExists(filespec)
TheFileExistsmethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
filespec
Required.Thenameofthefilewhoseexistenceistobedetermined.Acompletepathspecification(eitherabsoluteorrelative)mustbeprovidedifthefileisn'texpectedtoexistinthecurrentfolder.
Remarks
ThefollowingexampleillustratesuseoftheFileExistsmethod:
FunctionReportFileStatus(filespec)Dimfso,msgSetfso=CreateObject("Scripting.FileSystemObject")If(fso.FileExists(filespec))Thenmsg=filespec&"exists."Elsemsg=filespec&"doesn'texist."EndIfReportFileStatus=msg
EndFunction
Microsoft®VisualBasic®ScriptingEditionFileObject
ScriptingRun-TimeReferenceVersion3
SeeAlsoPropertiesMethods
Description
Providesaccesstoallthepropertiesofafile.
Remarks
ThefollowingcodeillustrateshowtoobtainaFileobjectandhowtoviewoneofitsproperties.
FunctionShowDateCreated(filespec)Dimfso,fSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFile(filespec)ShowDateCreated=f.DateCreatedEndFunction
Microsoft®VisualBasic®ScriptingEditionFilesCollection
ScriptingRun-TimeReferenceVersion3
SeeAlsoPropertiesMethods
Description
CollectionofallFileobjectswithinafolder.
Remarks
ThefollowingcodeillustrateshowtogetaFilescollectionanditeratethecollectionusingtheForEach...Nextstatement:
FunctionShowFolderList(folderspec)Dimfso,f,f1,fc,sSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFolder(folderspec)Setfc=f.FilesForEachf1infcs=s&f1.names=s&"<BR>"NextShowFolderList=sEndFunction
Microsoft®VisualBasic®ScriptingEditionFilesProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
ReturnsaFilescollectionconsistingofallFileobjectscontainedinthespecifiedfolder,includingthosewithhiddenandsystemfileattributesset.
Syntax
object.Files
TheobjectisalwaysaFolderobject.
Remarks
ThefollowingcodeillustratestheuseoftheFilesproperty:
FunctionShowFileList(folderspec)Dimfso,f,f1,fc,sSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFolder(folderspec)Setfc=f.FilesForEachf1infcs=s&f1.names=s&"<BR>"NextShowFileList=sEndFunction
Microsoft®VisualBasic®ScriptingEdition
FileSystemObjectObject
ScriptingRun-TimeReferenceVersion2
SeeAlsoPropertiesMethods
Description
Providesaccesstoacomputer'sfilesystem.
Remarks
ThefollowingcodeillustrateshowtheFileSystemObjectisusedtoreturnaTextStreamobjectthatcanbereadfromorwrittento:
Dimfso,MyFileSetfso=CreateObject("Scripting.FileSystemObject")SetMyFile=fso.CreateTextFile("c:\testfile.txt",True)MyFile.WriteLine("Thisisatest.")MyFile.Close
Intheprecedingcode,theCreateObjectfunctionreturnstheFileSystemObject(fso).TheCreateTextFilemethodthencreatesthefileasaTextStreamobject(a)andtheWriteLinemethodwritesalineoftexttothecreatedtextfile.TheClosemethodflushesthebufferandclosesthefile.
Microsoft®VisualBasic®ScriptingEdition
FileSystemObjectConstants
ScriptingRun-TimeReferenceVersion2
SeeAlso
FileSystemObjecthasanumberofusefulconstantsthatyoucanuseinyourcode.Constantsprovideaconvenientwaytousespecificvalueswithoutactuallyhavingtorememberthevalueitself.Theyalsomakesyourcodemoremaintainable,shouldthevalueofanyconstanteverchange.
Dependingonyourscriptinghost,theseconstantsmaybealreadydefined.Ifso,simplyusetheconstantsanywhereinyourcodeinplaceofthevaluestheyrepresent.IncaseswhereSCRRUN.DLLisnotexplicitlyreferencedbyyourscriptinghost,you'llhavetodefinetheseconstantsinyourcodebeforeyoucanusethem.ExamplesofthiscaseincludeMicrosoftInternetExplorerandMicrosoftInternetInformationServices(IIS).
ThefollowinglistdescribesthevariouscategoriesofconstantsprovidedfortheFileSystemObject,alongwithabriefdescription:
DriveTypeConstantsDefinesthevariousdrivetypesavailableonthehostcomputer,suchasFixed,Removable,CD-ROM,etc.
FileAttributeConstantsDefinesvariousfileattributessuchasHidden,Read-Only,etc.
FileInput/OutputConstantsDefinesconstantsusedwithfileinputandoutput.
SpecialFolderConstantsDefinesspecialfoldersavailableinyouroperatingsystem.
Microsoft®VisualBasic®ScriptingEdition
FileSystemProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnsthetypeoffilesysteminuseforthespecifieddrive.
Syntax
object.FileSystem
TheobjectisalwaysaDriveobject.
Remarks
AvailablereturntypesincludeFAT,NTFS,andCDFS.
ThefollowingcodeillustratestheuseoftheFileSystemproperty:
FunctionShowFileSystemType(drvspec)Dimfso,dSetfso=CreateObject("Scripting.FileSystemObject")Setd=fso.GetDrive(drvspec)ShowFileSystemType=d.FileSystemEndFunction
Microsoft®VisualBasic®ScriptingEditionFolderObject
ScriptingRun-TimeReferenceVersion3
SeeAlsoPropertiesMethods
Description
Providesaccesstoallthepropertiesofafolder.
Remarks
ThefollowingcodeillustrateshowtoobtainaFolderobjectandhowtoreturnoneofitsproperties:
FunctionShowDateCreated(folderspec)Dimfso,fSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFolder(folderspec)ShowDateCreated=f.DateCreatedEndFunction
Microsoft®VisualBasic®ScriptingEditionFoldersCollection
ScriptingRun-TimeReferenceVersion3
SeeAlsoPropertiesMethods
Description
CollectionofallFolderobjectscontainedwithinaFolderobject.
Remarks
ThefollowingcodeillustrateshowtogetaFolderscollectionandhowtoiteratethecollectionusingtheForEach...Nextstatement:
FunctionShowFolderList(folderspec)Dimfso,f,f1,fc,sSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFolder(folderspec)Setfc=f.SubFoldersForEachf1infcs=s&f1.names=s&"<BR>"NextShowFolderList=sEndFunction
Microsoft®VisualBasic®ScriptingEdition
FolderExistsMethod
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
ReturnsTrueifaspecifiedfolderexists;Falseifitdoesnot.
Syntax
object.FolderExists(folderspec)
TheFolderExistsmethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
folderspec
Required.Thenameofthefolderwhoseexistenceistobedetermined.Acompletepathspecification(eitherabsoluteorrelative)mustbeprovidedifthefolderisn'texpectedtoexistinthecurrentfolder.
Remarks
ThefollowingexampleillustratesuseoftheFolderExistsmethod:
FunctionReportFolderStatus(fldr)Dimfso,msgSetfso=CreateObject("Scripting.FileSystemObject")If(fso.FolderExists(fldr))Thenmsg=fldr&"exists."Elsemsg=fldr&"doesn'texist."
EndIfReportFolderStatus=msgEndFunction
Microsoft®VisualBasic®ScriptingEdition
FreeSpaceProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnstheamountoffreespaceavailabletoauseronthespecifieddriveornetworkshare.Read-only.
Syntax
object.FreeSpace
TheobjectisalwaysaDriveobject.
Remarks
ThevaluereturnedbytheFreeSpacepropertyistypicallythesameasthatreturnedbytheAvailableSpaceproperty.Differencesmayoccurbetweenthetwoforcomputersystemsthatsupportquotas.
ThefollowingcodeillustratestheuseoftheFreeSpaceproperty:
FunctionShowFreeSpace(drvPath)Dimfso,d,sSetfso=CreateObject("Scripting.FileSystemObject")Setd=fso.GetDrive(fso.GetDriveName(drvPath))s="Drive"&UCase(drvPath)&"-"s=s&d.VolumeName&"<BR>"s=s&"FreeSpace:"&FormatNumber(d.FreeSpace/1024,0)s=s&"Kbytes"ShowFreeSpace=sEndFunction
Microsoft®VisualBasic®ScriptingEdition
GetAbsolutePathNameMethod
ScriptingRun-TimeReference
Version3
SeeAlsoAppliesTo
Description
Returnsacompleteandunambiguouspathfromaprovidedpathspecification.
Syntax
object.GetAbsolutePathName(pathspec)
TheGetAbsolutePathNamemethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
pathspec Required.Pathspecificationtochangetoacompleteandunambiguouspath.
Remarks
Apathiscompleteandunambiguousifitprovidesacompletereferencefromtherootofthespecifieddrive.Acompletepathcanonlyendwithapathseparatorcharacter(\)ifitspecifiestherootfolderofamappeddrive.
Assumingthecurrentdirectoryisc:\mydocuments\reports,thefollowingtableillustratesthebehavioroftheGetAbsolutePathNamemethod.
pathspec Returnedpath"c:" "c:\mydocuments\reports""c:.." "c:\mydocuments""c:\\\" "c:\"
"c:*.*\may97" "c:\mydocuments\reports\*.*\may97""region1" "c:\mydocuments\reports\region1""c:\..\..\mydocuments" "c:\mydocuments"
Microsoft®VisualBasic®ScriptingEdition
GetBaseNameMethod
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnsastringcontainingthebasenameofthefile(lessanyfileextension),orfolderinaprovidedpathspecification.
Syntax
object.GetBaseName(path)
TheGetBaseNamemethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
path Required.Thepathspecificationforthefileorfolderwhosebasenameistobereturned.
Remarks
TheGetBaseNamemethodreturnsazero-lengthstring("")ifnofileorfoldermatchesthepathargument.
ThefollowingexampleillustratesuseoftheGetBaseNamemethod:
FunctionGetTheBase(filespec)DimfsoSetfso=CreateObject("Scripting.FileSystemObject")GetTheBase=fso.GetBaseName(filespec)EndFunction
NoteTheGetBaseNamemethodworksonlyontheprovidedpathstring.Itdoesnotattempttoresolvethepath,nordoesitcheckfortheexistenceofthespecifiedpath.
Microsoft®VisualBasic®ScriptingEdition
GetDriveMethodScriptingRun-TimeReference
Version3
SeeAlsoAppliesTo
Description
ReturnsaDriveobjectcorrespondingtothedriveinaspecifiedpath.
Syntax
object.GetDrivedrivespec
TheGetDrivemethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
drivespec
Required.Thedrivespecargumentcanbeadriveletter(c),adriveletterwithacolonappended(c:),adriveletterwithacolonandpathseparatorappended(c:\),oranynetworksharespecification(\\computer2\share1).
Remarks
Fornetworkshares,acheckismadetoensurethattheshareexists.
Anerroroccursifdrivespecdoesnotconformtooneoftheacceptedformsordoesnotexist.TocalltheGetDrivemethodonanormalpathstring,usethefollowingsequencetogetastringthatissuitableforuseasdrivespec:
DriveSpec=GetDriveName(GetAbsolutePathName(Path))
ThefollowingexampleillustratesuseoftheGetDrivemethod:
FunctionShowFreeSpace(drvPath)Dimfso,d,sSetfso=CreateObject("Scripting.FileSystemObject")
Setd=fso.GetDrive(fso.GetDriveName(drvPath))s="Drive"&UCase(drvPath)&"-"s=s&d.VolumeName&"<BR>"s=s&"FreeSpace:"&FormatNumber(d.FreeSpace/1024,0)s=s&"Kbytes"ShowFreeSpace=sEndFunction
Microsoft®VisualBasic®ScriptingEdition
GetDriveNameMethod
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnsastringcontainingthenameofthedriveforaspecifiedpath.
Syntax
object.GetDriveName(path)
TheGetDriveNamemethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
path Required.Thepathspecificationforthecomponentwhosedrivenameistobereturned.
Remarks
TheGetDriveNamemethodreturnsazero-lengthstring("")ifthedrivecan'tbedetermined.
ThefollowingexampleillustratesuseoftheGetDriveNamemethod:
FunctionGetAName(DriveSpec)DimfsoSetfso=CreateObject("Scripting.FileSystemObject")GetAName=fso.GetDriveName(Drivespec)EndFunction
NoteTheGetDriveNamemethodworksonlyontheprovidedpathstring.Itdoesnotattempttoresolvethepath,nordoesitcheckfortheexistenceofthespecifiedpath.
Microsoft®VisualBasic®ScriptingEdition
GetExtensionNameMethod
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnsastringcontainingtheextensionnameforthelastcomponentinapath.
Syntax
object.GetExtensionName(path)
TheGetExtensionNamemethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
path Required.Thepathspecificationforthecomponentwhoseextensionnameistobereturned.
Remarks
Fornetworkdrives,therootdirectory(\)isconsideredtobeacomponent.
TheGetExtensionNamemethodreturnsazero-lengthstring("")ifnocomponentmatchesthepathargument.
ThefollowingexampleillustratesuseoftheGetExtensionNamemethod:
FunctionGetAnExtension(DriveSpec)DimfsoSetfso=CreateObject("Scripting.FileSystemObject")GetAnExtension=fso.GetExtensionName(Drivespec
EndFunction
Microsoft®VisualBasic®ScriptingEditionGetFileMethod
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
ReturnsaFileobjectcorrespondingtothefileinaspecifiedpath.
Syntax
object.GetFile(filespec)
TheGetFilemethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
filespec Required.Thefilespecisthepath(absoluteorrelative)toaspecificfile.
Remarks
Anerroroccursifthespecifiedfiledoesnotexist.
ThefollowingexampleillustratesuseoftheGetFilemethod:
FunctionShowFileAccessInfo(filespec)Dimfso,f,sSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFile(filespec)s=f.Path&"<br>"s=s&"Created:"&f.DateCreated&"<br>"s=s&"LastAccessed:"&f.DateLastAccessed&"<br>"s=s&"LastModified:"&f.DateLastModifiedShowFileAccessInfo=s
EndFunction
Microsoft®VisualBasic®ScriptingEdition
GetFileNameMethod
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnsthelastfilenameorfolderofaspecifiedpaththatisnotpartofthedrivespecification.
Syntax
object.GetFileName(pathspec)
TheGetFileNamemethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
pathspec Required.Thepath(absoluteorrelative)toaspecificfile.
Remarks
TheGetFileNamemethodreturnsazero-lengthstring("")ifpathspecdoesnotendwiththenamedfileorfolder.
ThefollowingexampleillustratesuseoftheGetFileNamemethod:
FunctionGetAName(DriveSpec)DimfsoSetfso=CreateObject("Scripting.FileSystemObject")GetAName=fso.GetFileName(DriveSpec)EndFunction
NoteTheGetFileNamemethodworksonlyontheprovidedpathstring.Itdoesnotattempttoresolvethepath,nordoesitcheckfortheexistenceofthespecifiedpath.
Microsoft®VisualBasic®ScriptingEdition
GetFileVersionMethod
ScriptingRun-TimeReferenceVersion5
SeeAlsoAppliesTo
Description
Returnstheversionnumberofaspecifiedfile.
Syntax
object.GetFileVersion(pathspec)
TheGetVersionmethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
pathspec Required.Thepath(absoluteorrelative)toaspecificfile.
Remarks
TheGetFileVersionmethodreturnsazero-lengthstring("")ifpathspecdoesnotendwiththenamedfileorifthefiledoesnotcontainversioninformation.
ThefollowingexampleillustratesuseoftheGetFileVersionmethod:
FunctionGetVersion(PathSpec)Dimfso,tempSetfso=CreateObject("Scripting.FileSystemObject")temp=fso.GetFileVersion(PathSpec)IfLen(temp)Then
GetVersion=tempElseGetVersion="Noversioninformationavailable."EndIfEndFunction
NoteTheGetFileVersionmethodworksonlyontheprovidedpathstring.Itdoesnotattempttoresolvethepath,nordoesitcheckfortheexistenceofthespecifiedpath.
Microsoft®VisualBasic®ScriptingEdition
GetFolderMethodScriptingRun-TimeReference
Version3
SeeAlsoAppliesTo
Description
ReturnsaFolderobjectcorrespondingtothefolderinaspecifiedpath.
Syntax
object.GetFolder(folderspec)
TheGetFoldermethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
folderspec Required.Thefolderspecisthepath(absoluteorrelative)toaspecificfolder.
Remarks
Anerroroccursifthespecifiedfolderdoesnotexist.
ThefollowingexampleillustratestheuseoftheGetFoldermethodtoreturnafolderobject:
SubAddNewFolder(path,folderName)Dimfso,f,fc,nfSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFolder(path)Setfc=f.SubFoldersIffolderName<>""ThenSetnf=fc.Add(folderName)
ElseSetnf=fc.Add("NewFolder")EndIfEndSub
Microsoft®VisualBasic®ScriptingEdition
GetParentFolderNameMethod
ScriptingRun-TimeReference
Version3
SeeAlsoAppliesTo
Description
Returnsastringcontainingthenameoftheparentfolderofthelastfileorfolderinaspecifiedpath.
Syntax
object.GetParentFolderName(path)
TheGetParentFolderNamemethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
path Required.Thepathspecificationforthefileorfolderwhoseparentfoldernameistobereturned.
Remarks
TheGetParentFolderNamemethodreturnsazero-lengthstring("")ifthereisnoparentfolderforthefileorfolderspecifiedinthepathargument.
ThefollowingexampleillustratesuseoftheGetParentFolderNamemethod:
FunctionGetTheParent(DriveSpec)DimfsoSetfso=CreateObject("Scripting.FileSystemObject")GetTheParent=fso.GetParentFolderName(DrivespecEndFunction
NoteTheGetParentFolderNamemethodworksonlyontheprovidedpathstring.Itdoesnotattempttoresolvethepath,nordoesitcheckfortheexistenceofthespecifiedpath.
Microsoft®VisualBasic®ScriptingEdition
GetSpecialFolderMethod
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnsthespecialfolderspecified.
Syntax
object.GetSpecialFolder(folderspec)
TheGetSpecialFoldermethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
folderspecRequired.Thenameofthespecialfoldertobereturned.CanbeanyoftheconstantsshownintheSettingssection.
Settings
Thefolderspecargumentcanhaveanyofthefollowingvalues:
Constant Value Description
WindowsFolder 0TheWindowsfoldercontainsfilesinstalledbytheWindowsoperatingsystem.
SystemFolder 1 TheSystemfoldercontainslibraries,fonts,anddevicedrivers.
TemporaryFolder 2TheTempfolderisusedtostoretemporaryfiles.ItspathisfoundintheTMPenvironmentvariable.
Remarks
ThefollowingexampleillustratesuseoftheGetSpecialFoldermethod:
Dimfso,tempfileSetfso=CreateObject("Scripting.FileSystemObject")
FunctionCreateTempFileDimtfolder,tname,tfileConstTemporaryFolder=2Settfolder=fso.GetSpecialFolder(TemporaryFolder)tname=fso.GetTempNameSettfile=tfolder.CreateTextFile(tname)SetCreateTempFile=tfileEndFunction
Settempfile=CreateTempFiletempfile.WriteLine"HelloWorld"tempfile.Close
Microsoft®VisualBasic®ScriptingEdition
GetTempNameMethod
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnsarandomlygeneratedtemporaryfileorfoldernamethatisusefulforperformingoperationsthatrequireatemporaryfileorfolder.
Syntax
object.GetTempName
TheoptionalobjectisalwaysthenameofaFileSystemObject.
Remarks
TheGetTempNamemethoddoesnotcreateafile.ItprovidesonlyatemporaryfilenamethatcanbeusedwithCreateTextFiletocreateafile.
ThefollowingexampleillustratesuseoftheGetTempNamemethod:
Dimfso,tempfileSetfso=CreateObject("Scripting.FileSystemObject")
FunctionCreateTempFileDimtfolder,tname,tfileConstTemporaryFolder=2Settfolder=fso.GetSpecialFolder(TemporaryFolder)tname=fso.GetTempName
Settfile=tfolder.CreateTextFile(tname)SetCreateTempFile=tfileEndFunction
Settempfile=CreateTempFiletempfile.WriteLine"HelloWorld"tempfile.Close
Microsoft®VisualBasic®ScriptingEditionIsReadyProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
ReturnsTrueifthespecifieddriveisready;Falseifitisnot.
Syntax
object.IsReady
TheobjectisalwaysaDriveobject.
Remarks
Forremovable-mediadrivesandCD-ROMdrives,IsReadyreturnsTrueonlywhentheappropriatemediaisinsertedandreadyforaccess.
ThefollowingcodeillustratestheuseoftheIsReadyproperty:
FunctionShowDriveInfo(drvpath)Dimfso,d,s,tSetfso=CreateObject("Scripting.FileSystemObject")Setd=fso.GetDrive(drvpath)SelectCased.DriveTypeCase0:t="Unknown"Case1:t="Removable"Case2:t="Fixed"Case3:t="Network"Case4:t="CD-ROM"Case5:t="RAMDisk"EndSelects="Drive"&d.DriveLetter&":-"&t
Ifd.IsReadyThens=s&"<BR>"&"DriveisReady."Elses=s&"<BR>"&"DriveisnotReady."EndIfShowDriveInfo=sEndFunction
Microsoft®VisualBasic®ScriptingEdition
IsRootFolderProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
ReturnsTrueifthespecifiedfolderistherootfolder;Falseifitisnot.
Syntax
object.IsRootFolder
TheobjectisalwaysaFolderobject.
Remarks
ThefollowingcodeillustratestheuseoftheIsRootFolderproperty:
FunctionDisplayLevelDepth(pathspec)Dimfso,f,nSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFolder(pathspec)Iff.IsRootFolderThenDisplayLevelDepth="Thespecifiedfolderistherootfolder."ElseDoUntilf.IsRootFolderSetf=f.ParentFoldern=n+1LoopDisplayLevelDepth="Thespecifiedfolderisnested"&n&"levelsdeep."EndIfEndFunction
Microsoft®VisualBasic®ScriptingEditionItemProperty
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesTo
Description
SetsorreturnsanitemforaspecifiedkeyinaDictionaryobject.Forcollections,returnsanitembasedonthespecifiedkey.Read/write.
Syntax
object.Item(key)[=newitem]
TheItempropertyhasthefollowingparts:
Part Description
object Required.AlwaysthenameofacollectionorDictionaryobject.
key Required.Keyassociatedwiththeitembeingretrievedoradded.
newitemOptional.UsedforDictionaryobjectonly;noapplicationforcollections.Ifprovided,newitemisthenewvalueassociatedwiththespecifiedkey.
Remarks
Ifkeyisnotfoundwhenchanginganitem,anewkeyiscreatedwiththespecifiednewitem.Ifkeyisnotfoundwhenattemptingtoreturnanexistingitem,anewkeyiscreatedanditscorrespondingitemisleftempty.
ThefollowingexampleillustratestheuseoftheItemproperty:
FunctionItemDemo
Dimd'Createsomevariables.Setd=CreateObject("Scripting.Dictionary")d.Add"a","Athens"'Addsomekeysanditems.d.Add"b","Belgrade"d.Add"c","Cairo"ItemDemo=d.Item("c")'Gettheitem.EndFunction
Microsoft®VisualBasic®ScriptingEditionItemsMethod
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesto
Description
ReturnsanarraycontainingalltheitemsinaDictionaryobject.
Syntax
object.Items
TheobjectisalwaysthenameofaDictionaryobject.
Remarks
ThefollowingcodeillustratesuseoftheItemsmethod:
FunctionDicDemoDima,d,i,s'Createsomevariables.Setd=CreateObject("Scripting.Dictionary")d.Add"a","Athens"'Addsomekeysanditems.d.Add"b","Belgrade"d.Add"c","Cairo"a=d.Items'Gettheitems.Fori=0Tod.Count-1'Iteratethearray.s=s&a(i)&"<BR>"'Createreturnstring.NextDicDemo=sEndFunction
Microsoft®VisualBasic®ScriptingEditionKeyProperty
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesto
Description
SetsakeyinaDictionaryobject.
Syntax
object.Key(key)=newkey
TheKeypropertyhasthefollowingparts:
Part Descriptionobject Required.AlwaysthenameofaDictionaryobject.key Required.Keyvaluebeingchanged.newkey Required.Newvaluethatreplacesthespecifiedkey.
Remarks
Ifkeyisnotfoundwhenchangingakey,arun-timeerrorwilloccur.
ThefollowingexampleillustratestheuseoftheKeyproperty:
FunctionDicDemoDimd'Createsomevariables.Setd=CreateObject("Scripting.Dictionary")d.Add"a","Athens"'Addsomekeysanditems.d.Add"b","Belgrade"d.Add"c","Cairo"
d.Key("c")="d"'Setkeyfor"c"to"d".DicDemo=d.Item("d")'Returnassociateitem.EndFunction
Microsoft®VisualBasic®ScriptingEditionKeysMethod
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesto
Description
ReturnsanarraycontainingallexistingkeysinaDictionaryobject.
Syntax
object.Keys
TheobjectisalwaysthenameofaDictionaryobject.
Remarks
ThefollowingcodeillustratesuseoftheKeysmethod:
FunctionDicDemoDima,d,i'Createsomevariables.Setd=CreateObject("Scripting.Dictionary")d.Add"a","Athens"'Addsomekeysanditems.d.Add"b","Belgrade"d.Add"c","Cairo"a=d.Keys'Getthekeys.Fori=0Tod.Count-1'Iteratethearray.s=s&a(i)&"<BR>"'Returnresults.NextDicDemo=sEndFunction
Microsoft®VisualBasic®ScriptingEditionLineProperty
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesto
Description
Read-onlypropertythatreturnsthecurrentlinenumberinaTextStreamfile.
Syntax
object.Line
TheobjectisalwaysthenameofaTextStreamobject.
Remarks
Afterafileisinitiallyopenedandbeforeanythingiswritten,Lineisequalto1.
ThefollowingexampleillustratesuseoftheLineproperty:
FunctionGetLineConstForReading=1,ForWriting=2Dimfso,f,raSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.OpenTextFile("c:\testfile.txt",ForWriting,True)f.Write"Helloworld!"&vbCrLf&"VBScriptisfun!"&vbCrLfSetf=fso.OpenTextFile("c:\testfile.txt",ForReading)ra=f.ReadAllGetLine=f.LineEndFunction
Microsoft®VisualBasic®ScriptingEditionMoveMethod
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Movesaspecifiedfileorfolderfromonelocationtoanother.
Syntax
object.Movedestination
TheMovemethodsyntaxhastheseparts:
Part Description
object Required.AlwaysthenameofaFileorFolderobject.
destination Required.Destinationwherethefileorfolderistobemoved.Wildcardcharactersarenotallowed.
Remarks
TheresultsoftheMovemethodonaFileorFolderareidenticaltooperationsperformedusingFileSystemObject.MoveFileorFileSystemObject.MoveFolder.Youshouldnote,however,thatthealternativemethodsarecapableofmovingmultiplefilesorfolders.
ThefollowingexampleillustratesuseoftheMovemethod:
Dimfso,MyFileSetfso=CreateObject("Scripting.FileSystemObject")SetMyFile=fso.CreateTextFile("c:\testfile.txt",True)MyFile.WriteLine("Thisisatest.")
MyFile.CloseSetMyFile=fso.GetFile("c:\testfile.txt")MyFile.Move"c:\windows\desktop\"
Microsoft®VisualBasic®ScriptingEdition
MoveFileMethodScriptingRun-TimeReference
Version3
SeeAlsoAppliesTo
Description
Movesoneormorefilesfromonelocationtoanother.
Syntax
object.MoveFilesource,destination
TheMoveFilemethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
sourceRequired.Thepathtothefileorfilestobemoved.Thesourceargumentstringcancontainwildcardcharactersinthelastpathcomponentonly.
destinationRequired.Thepathwherethefileorfilesaretobemoved.Thedestinationargumentcan'tcontainwildcardcharacters.
Remarks
Ifsourcecontainswildcardsordestinationendswithapathseparator(\),itisassumedthatdestinationspecifiesanexistingfolderinwhichtomovethematchingfiles.Otherwise,destinationisassumedtobethenameofadestinationfiletocreate.Ineithercase,threethingscanhappenwhenanindividualfileismoved:
Ifdestinationdoesnotexist,thefilegetsmoved.Thisistheusualcase.
Ifdestinationisanexistingfile,anerroroccurs.
Ifdestinationisadirectory,anerroroccurs.
Anerroralsooccursifawildcardcharacterthatisusedinsourcedoesn'tmatchanyfiles.TheMoveFilemethodstopsonthefirsterroritencounters.Noattemptismadetorollbackanychangesmadebeforetheerroroccurs.
ThefollowingexampleillustratesuseoftheMoveFilemethod:
SubMoveAFile(Drivespec)DimfsoSetfso=CreateObject("Scripting.FileSystemObject")fso.MoveFileDrivespec,"c:\windows\desktop\"EndSub
ImportantThismethodallowsmovingfilesbetweenvolumesonlyifsupportedbytheoperatingsystem.
Microsoft®VisualBasic®ScriptingEdition
MoveFolderMethod
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Movesoneormorefoldersfromonelocationtoanother.
Syntax
object.MoveFoldersource,destination
TheMoveFoldermethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
sourceRequired.Thepathtothefolderorfolderstobemoved.Thesourceargumentstringcancontainwildcardcharactersinthelastpathcomponentonly.
destinationRequired.Thepathwherethefolderorfoldersaretobemoved.Thedestinationargumentcan'tcontainwildcardcharacters.
Remarks
Ifsourcecontainswildcardsordestinationendswithapathseparator(\),itisassumedthatdestinationspecifiesanexistingfolderinwhichtomovethematchingfiles.Otherwise,destinationisassumedtobethenameofadestinationfoldertocreate.Ineithercase,threethingscanhappenwhenanindividualfolderismoved:
Ifdestinationdoesnotexist,thefoldergetsmoved.Thisistheusualcase.
Ifdestinationisanexistingfile,anerroroccurs.
Ifdestinationisadirectory,anerroroccurs.
Anerroralsooccursifawildcardcharacterthatisusedinsourcedoesn'tmatchanyfolders.TheMoveFoldermethodstopsonthefirsterroritencounters.Noattemptismadetorollbackanychangesmadebeforetheerroroccurs.
ThefollowingexampleillustratesuseoftheMoveFoldermethod:
SubMoveAFolder(Drivespec)DimfsoSetfso=CreateObject("Scripting.FileSystemObject")fso.MoveFolderDrivespec,"c:\windows\desktop\"EndSub
ImportantThismethodallowsmovingfoldersbetweenvolumesonlyifsupportedbytheoperatingsystem.
Microsoft®VisualBasic®ScriptingEditionNameProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Setsorreturnsthenameofaspecifiedfileorfolder.Read/write.
Syntax
object.Name[=newname]
TheNamepropertyhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileorFolderobject.
newname Optional.Ifprovided,newnameisthenewnameofthespecifiedobject.
Remarks
ThefollowingcodeillustratestheuseoftheNameproperty:
FunctionShowFileAccessInfo(filespec)Dimfso,f,sSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFile(filespec)s=f.Name&"onDrive"&UCase(f.Drive)&"<BR>"s=s&"Created:"&f.DateCreated&"<BR>"s=s&"LastAccessed:"&f.DateLastAccessed&"<BR>"s=s&"LastModified:"&f.DateLastModifiedShowFileAccessInfo=sEndFunction
Microsoft®VisualBasic®ScriptingEdition
OpenAsTextStreamMethod
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
OpensaspecifiedfileandreturnsaTextStreamobjectthatcanbeusedtoreadfrom,writeto,orappendtothefile.
Syntax
object.OpenAsTextStream([iomode,[format]])
TheOpenAsTextStreammethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileobject.
iomodeOptional.Indicatesinput/outputmode.Canbeoneofthreeconstants:ForReading,ForWriting,orForAppending.
formatOptional.OneofthreeTristatevaluesusedtoindicatetheformatoftheopenedfile.Ifomitted,thefileisopenedasASCII.
Settings
Theiomodeargumentcanhaveanyofthefollowingsettings:
Constant Value Description
ForReading 1 Openafileforreadingonly.Youcan'twritetothisfile.
ForWriting 2Openafileforwriting.Ifafilewiththesamenameexists,itspreviouscontents
areoverwritten.
ForAppending 8 Openafileandwritetotheendofthefile.
Theformatargumentcanhaveanyofthefollowingsettings:
Constant Value Description
TristateUseDefault -2 Opensthefileusingthesystemdefault.
TristateTrue -1 OpensthefileasUnicode.TristateFalse 0 OpensthefileasASCII.
Remarks
TheOpenAsTextStreammethodprovidesthesamefunctionalityastheOpenTextFilemethodoftheFileSystemObject.Inaddition,theOpenAsTextStreammethodcanbeusedtowritetoafile.
ThefollowingcodeillustratestheuseoftheOpenAsTextStreammethod:
FunctionTextStreamTestConstForReading=1,ForWriting=2,ForAppending=8ConstTristateUseDefault=-2,TristateTrue=-1,TristateFalse=0Dimfso,f,tsSetfso=CreateObject("Scripting.FileSystemObject")fso.CreateTextFile"test1.txt"'Createafile.Setf=fso.GetFile("test1.txt")Setts=f.OpenAsTextStream(ForWriting,TristateUseDefaultts.Write"HelloWorld"ts.CloseSetts=f.OpenAsTextStream(ForReading,TristateUseDefault
TextStreamTest=ts.ReadLinets.CloseEndFunction
Microsoft®VisualBasic®ScriptingEdition
OpenTextFileMethod
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesTo
Description
OpensaspecifiedfileandreturnsaTextStreamobjectthatcanbeusedtoreadfrom,writeto,orappendtothefile.
Syntax
object.OpenTextFile(filename[,iomode[,create[,format]]])
TheOpenTextFilemethodhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaFileSystemObject.
filename Required.Stringexpressionthatidentifiesthefiletoopen.
iomodeOptional.Indicatesinput/outputmode.Canbeoneofthreeconstants:ForReading,ForWriting,orForAppending.
create
Optional.Booleanvaluethatindicateswhetheranewfilecanbecreatedifthespecifiedfilenamedoesn'texist.ThevalueisTrueifanewfileiscreated;Falseifitisn'tcreated.ThedefaultisFalse.
formatOptional.OneofthreeTristatevaluesusedtoindicatetheformatoftheopenedfile.Ifomitted,thefileisopenedasASCII.
Settings
Theiomodeargumentcanhaveeitherofthefollowingsettings:
Constant Value Description
ForReading 1 Openafileforreadingonly.Youcan'twritetothisfile.
ForWriting 2 Openafileforwritingonly.Youcan'treadfromthisfile.
ForAppending 8 Openafileandwritetotheendofthefile.
Theformatargumentcanhaveanyofthefollowingsettings:
Constant Value Description
TristateUseDefault -2 Opensthefileusingthesystemdefault.
TristateTrue -1 OpensthefileasUnicode.TristateFalse 0 OpensthefileasASCII.
Remarks
ThefollowingcodeillustratestheuseoftheOpenTextFilemethodtoopenafileforwritingtext:
SubOpenTextFileTestConstForReading=1,ForWriting=2,ForAppending=8Dimfso,fSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.OpenTextFile("c:\testfile.txt",ForWriting,True)f.Write"Helloworld!"f.CloseEndSub
Microsoft®VisualBasic®ScriptingEdition
ParentFolderProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnsthefolderobjectfortheparentofthespecifiedfileorfolder.Read-only.
Syntax
object.ParentFolder
TheobjectisalwaysaFileorFolderobject.
Remarks
ThefollowingcodeillustratestheuseoftheParentFolderpropertywithafile:
FunctionShowFileAccessInfo(filespec)Dimfso,f,sSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFile(filespec)s=UCase(f.Name)&"in"&UCase(f.ParentFolder)&"<BR>"s=s&"Created:"&f.DateCreated&"<BR>"s=s&"LastAccessed:"&f.DateLastAccessed&"<BR>"s=s&"LastModified:"&f.DateLastModifiedShowFileAccessInfo=sEndFunction
Microsoft®VisualBasic®ScriptingEditionPathProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnsthepathforaspecifiedfile,folder,ordrive.
Syntax
object.Path
TheobjectisalwaysaFile,Folder,orDriveobject.
Remarks
Fordriveletters,therootdriveisnotincluded.Forexample,thepathfortheCdriveisC:,notC:\.
ThefollowingcodeillustratestheuseofthePathpropertywithaFileobject:
FunctionShowFileAccessInfo(filespec)Dimfso,d,f,sSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFile(filespec)s=UCase(f.Path)&"<BR>"s=s&"Created:"&f.DateCreated&"<BR>"s=s&"LastAccessed:"&f.DateLastAccessed&"<BR>"s=s&"LastModified:"&f.DateLastModifiedShowFileAccessInfo=sEndFunction
Microsoft®VisualBasic®ScriptingEditionReadMethod
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesto
Description
ReadsaspecifiednumberofcharactersfromaTextStreamfileandreturnstheresultingstring.
Syntax
object.Read(characters)
TheReadmethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaTextStreamobject.
characters Required.Numberofcharactersyouwanttoreadfromthefile.
Remarks
ThefollowingexampleillustrateshowtousetheReadmethodtoreadfivecharactersfromafileandreturntheresultingstring:
FunctionReadTextFileTestConstForReading=1,ForWriting=2,ForAppending=8Dimfso,f,MsgSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.OpenTextFile("c:\testfile.txt",ForWriting,True)
f.Write"Helloworld!"Setf=fso.OpenTextFile("c:\testfile.txt",ForReading)ReadTextFileTest=f.Read(5)EndFunction
Microsoft®VisualBasic®ScriptingEditionReadAllMethod
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesto
Description
ReadsanentireTextStreamfileandreturnstheresultingstring.
Syntax
object.ReadAll
TheobjectisalwaysthenameofaTextStreamobject.
Remarks
Forlargefiles,usingtheReadAllmethodwastesmemoryresources.Othertechniquesshouldbeusedtoinputafile,suchasreadingafilelinebyline.
FunctionReadAllTextFileConstForReading=1,ForWriting=2Dimfso,fSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.OpenTextFile("c:\testfile.txt",ForWriting,True)f.Write"Helloworld!"Setf=fso.OpenTextFile("c:\testfile.txt",ForReading)ReadAllTextFile=f.ReadAllEndFunction
Microsoft®VisualBasic®ScriptingEdition
ReadLineMethodScriptingRun-TimeReference
Version2
SeeAlsoAppliesto
Description
Readsanentireline(upto,butnotincluding,thenewlinecharacter)fromaTextStreamfileandreturnstheresultingstring.
Syntax
object.ReadLine
TheobjectargumentisalwaysthenameofaTextStreamobject.
Remarks
ThefollowingexampleshowshowtousetheReadLinemethodtoreadalinefromaTextStreamfileandreturnthestring:
FunctionReadLineTextFileConstForReading=1,ForWriting=2Dimfso,MyFileSetfso=CreateObject("Scripting.FileSystemObject")SetMyFile=fso.OpenTextFile("c:\testfile.txt",ForWriting,True)MyFile.WriteLine"Helloworld!"MyFile.WriteLine"Thequickbrownfox"MyFile.CloseSetMyFile=fso.OpenTextFile("c:\testfile.txt",ForReading)ReadLineTextFile=MyFile.ReadLine'Returns"Helloworld!"EndFunction
Microsoft®VisualBasic®ScriptingEditionRemoveMethod
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesto
Description
Removesakey,itempairfromaDictionaryobject.
Syntax
object.Remove(key)
TheRemovemethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaDictionaryobject.
key Required.Keyassociatedwiththekey,itempairyouwanttoremovefromtheDictionaryobject.
Remarks
Anerroroccursifthespecifiedkey,itempairdoesnotexist.
ThefollowingcodeillustratesuseoftheRemovemethod:
Dima,d'Createsomevariables.Setd=CreateObject("Scripting.Dictionary")d.Add"a","Athens"'Addsomekeysanditems.d.Add"b","Belgrade"d.Add"c","Cairo"...
d.Remove("b")'Removesecondpair.
Microsoft®VisualBasic®ScriptingEdition
RemoveAllMethod
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesto
Description
TheRemoveAllmethodremovesallkey,itempairsfromaDictionaryobject.
Syntax
object.RemoveAll
TheobjectisalwaysthenameofaDictionaryobject.
Remarks
ThefollowingcodeillustratesuseoftheRemoveAllmethod:
Dima,d,i'Createsomevariables.Setd=CreateObject("Scripting.Dictionary")d.Add"a","Athens"'Addsomekeysanditems.d.Add"b","Belgrade"d.Add"c","Cairo"...a=d.RemoveAll'Clearthedictionary.
Microsoft®VisualBasic®ScriptingEdition
RootFolderProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
ReturnsaFolderobjectrepresentingtherootfolderofaspecifieddrive.Read-only.
Syntax
object.RootFolder
TheobjectisalwaysaDriveobject.
Remarks
AllthefilesandfolderscontainedonthedrivecanbeaccessedusingthereturnedFolderobject.
ThefollowingexampleillustratestheuseoftheRootFolderproperty:
FunctionShowRootFolder(drvspec)Dimfso,fSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetDrive(drvspec)ShowRootFolder=f.RootFolderEndFunction
Microsoft®VisualBasic®ScriptingEdition
SerialNumberProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnsthedecimalserialnumberusedtouniquelyidentifyadiskvolume.
Syntax
object.SerialNumber
TheobjectisalwaysaDriveobject.
Remarks
YoucanusetheSerialNumberpropertytoensurethatthecorrectdiskisinsertedinadrivewithremovablemedia.
ThefollowingcodeillustratestheuseoftheSerialNumberproperty:
FunctionShowDriveInfo(drvpath)Dimfso,d,s,tSetfso=CreateObject("Scripting.FileSystemObject")Setd=fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(drvpath)))SelectCased.DriveTypeCase0:t="Unknown"Case1:t="Removable"Case2:t="Fixed"Case3:t="Network"Case4:t="CD-ROM"Case5:t="RAMDisk"EndSelect
s="Drive"&d.DriveLetter&":-"&ts=s&"<BR>"&"SN:"&d.SerialNumberShowDriveInfo=sEndFunction
Microsoft®VisualBasic®ScriptingEdition
ShareNameProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnsthenetworksharenameforaspecifieddrive.
Syntax
object.ShareName
TheobjectisalwaysaDriveobject.
Remarks
Ifobjectisnotanetworkdrive,theShareNamepropertyreturnsazero-lengthstring("").
ThefollowingcodeillustratestheuseoftheShareNameproperty:
FunctionShowDriveInfo(drvpath)Dimfso,dSetfso=CreateObject("Scripting.FileSystemObject")Setd=fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(drvpath)))ShowDriveInfo="Drive"&d.DriveLetter&":-"&d.ShareNameEndFunction
Microsoft®VisualBasic®ScriptingEdition
ShortNameProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnstheshortnameusedbyprogramsthatrequiretheearlier8.3namingconvention.
Syntax
object.ShortName
TheobjectisalwaysaFileorFolderobject.
Remarks
ThefollowingcodeillustratestheuseoftheShortNamepropertywithaFileobject:
FunctionShowShortName(filespec)Dimfso,f,sSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFile(filespec)s="Theshortnamefor"&UCase(f.Name)&"<BR>"s=s&"is:"&f.ShortNameShowShortName=sEndFunction
Microsoft®VisualBasic®ScriptingEdition
ShortPathProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnstheshortpathusedbyprogramsthatrequiretheearlier8.3filenamingconvention.
Syntax
object.ShortPath
TheobjectisalwaysaFileorFolderobject.
Remarks
ThefollowingcodeillustratestheuseoftheShortNamepropertywithaFileobject:
FunctionShowShortPath(filespec)Dimfso,f,sSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFile(filespec)s="Theshortpathfor"&UCase(f.Name)&"<BR>"s=s&"is:"&f.ShortPathShowShortPath=sEndFunction
Microsoft®VisualBasic®ScriptingEditionSizeProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Forfiles,returnsthesize,inbytes,ofthespecifiedfile.Forfolders,returnsthesize,inbytes,ofallfilesandsubfolderscontainedinthefolder.
Syntax
object.Size
TheobjectisalwaysaFileorFolderobject.
Remarks
ThefollowingcodeillustratestheuseoftheSizepropertywithaFolderobject:
FunctionShowFolderSize(filespec)Dimfso,f,sSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFolder(filespec)s=UCase(f.Name)&"uses"&f.size&"bytes."ShowFolderSize=sEndFunction
Microsoft®VisualBasic®ScriptingEditionSkipMethod
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesTo
Description
SkipsaspecifiednumberofcharacterswhenreadingaTextStreamfile.
Syntax
object.Skip(characters)
TheSkipmethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaTextStreamobject.
characters Required.Numberofcharacterstoskipwhenreadingafile.
Remarks
Skippedcharactersarediscarded.
ThefollowingexampleusestheSkipmethodtoskipthefirstsixcharactersbeforereadingfromatextfile:
FunctionSkipTextFileConstForReading=1,ForWriting=2Dimfso,fSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.OpenTextFile("c:\testfile.txt",ForWriting,True)f.Write"Helloworld!"
Setf=fso.OpenTextFile("c:\testfile.txt",ForReading)f.Skip(6)SkipTextFile=f.ReadLineEndFunction
Microsoft®VisualBasic®ScriptingEdition
SkipLineMethodScriptingRun-TimeReference
Version2
SeeAlsoAppliesto
Description
SkipsthenextlinewhenreadingaTextStreamfile.
Syntax
object.SkipLine
TheobjectisalwaysthenameofaTextStreamobject.
Remarks
Skippingalinemeansreadinganddiscardingallcharactersinalineuptoandincludingthenextnewlinecharacter.Anerroroccursifthefileisnotopenforreading.
ThefollowingexampleillustratesuseoftheSkipLinemethod:
FunctionSkipLineInFileConstForReading=1,ForWriting=2Dimfso,fSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.OpenTextFile("c:\testfile.txt",ForWriting,True)f.Write"Helloworld!"&vbCrLf&"VBScriptisfun!"Setf=fso.OpenTextFile("c:\testfile.txt",ForReading)f.SkipLineSkipLineInFile=f.ReadLineEndFunction
Microsoft®VisualBasic®ScriptingEdition
SpecialFolderConstants
ScriptingRun-TimeReferenceVersion3
SeeAlso
Theseconstantsareonlyavailablewhenyourprojecthasanexplicitreferencetotheappropriatetypelibrarycontainingtheseconstantdefinitions.ForVBScript,youmustexplicitlydeclaretheseconstantsinyourcode.
Constant Value Description
WindowsFolder 0TheWindowsfoldercontainsfilesinstalledbytheWindowsoperatingsystem.
SystemFolder 1 TheSystemfoldercontainslibraries,fonts,anddevicedrivers.
TemporaryFolder 2TheTempfolderisusedtostoretemporaryfiles.ItspathisfoundintheTMPenvironmentvariable.
Microsoft®VisualBasic®ScriptingEdition
SubFoldersProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
ReturnsaFolderscollectionconsistingofallfolderscontainedinaspecifiedfolder,includingthosewithHiddenandSystemfileattributesset.
Syntax
object.SubFolders
TheobjectisalwaysaFolderobject.
Remarks
ThefollowingcodeillustratestheuseoftheSubFoldersproperty:
FunctionShowFolderList(folderspec)Dimfso,f,f1,s,sfSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFolder(folderspec)Setsf=f.SubFoldersForEachf1insfs=s&f1.names=s&"<BR>"NextShowFolderList=sEndFunction
Microsoft®VisualBasic®ScriptingEdition
TextStreamObjectScriptingRun-TimeReference
Version2
SeeAlsoPropertiesMethods
Description
Facilitatessequentialaccesstoafile.
Remarks
Inthefollowingcode,aistheTextStreamobjectreturnedbytheCreateTextFilemethodontheFileSystemObject:
Dimfso,MyFileSetfso=CreateObject("Scripting.FileSystemObject")SetMyFile=fso.CreateTextFile("c:\testfile.txt",True)MyFile.WriteLine("Thisisatest.")MyFile.Close
WriteLineandClosearetwomethodsoftheTextStreamObject.
Microsoft®VisualBasic®ScriptingEdition
TotalSizePropertyScriptingRun-TimeReference
Version3
SeeAlsoAppliesTo
Description
Returnsthetotalspace,inbytes,ofadriveornetworkshare.
Syntax
object.TotalSize
TheobjectisalwaysaDriveobject.
Remarks
ThefollowingcodeillustratestheuseoftheTotalSizeproperty:
FunctionShowSpaceInfo(drvpath)Dimfso,d,sSetfso=CreateObject("Scripting.FileSystemObject")Setd=fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(drvpath)))s="Drive"&d.DriveLetter&":"s=s&vbCrLfs=s&"TotalSize:"&FormatNumber(d.TotalSize/1024,0)&"Kbytes"s=s&vbCrLfs=s&"Available:"&FormatNumber(d.AvailableSpace/1024,0)&"Kbytes"ShowSpaceInfo=sEndFunction
Microsoft®VisualBasic®ScriptingEditionTypeProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Returnsinformationaboutthetypeofafileorfolder.Forexample,forfilesendingin.TXT,"TextDocument"isreturned.
Syntax
object.Type
TheobjectisalwaysaFileorFolderobject.
Remarks
ThefollowingcodeillustratestheuseoftheTypepropertytoreturnafoldertype.Inthisexample,tryprovidingthepathoftheRecycleBinorotheruniquefoldertotheprocedure.
FunctionShowFolderType(filespec)Dimfso,f,sSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.GetFolder(filespec)s=UCase(f.Name)&"isa"&f.TypeShowFolderType=sEndFunction
Microsoft®VisualBasic®ScriptingEdition
VolumeNameProperty
ScriptingRun-TimeReferenceVersion3
SeeAlsoAppliesTo
Description
Setsorreturnsthevolumenameofthespecifieddrive.Read/write.
Syntax
object.VolumeName[=newname]
TheVolumeNamepropertyhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaDriveobject.
newname Optional.Ifprovided,newnameisthenewnameofthespecifiedobject.
Remarks
ThefollowingcodeillustratestheuseoftheVolumeNameproperty:
FunctionShowVolumeInfo(drvpath)Dimfso,d,sSetfso=CreateObject("Scripting.FileSystemObject")Setd=fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(drvpath)))s="Drive"&d.DriveLetter&":-"&d.VolumeNameShowVolumeInfo=sEndFunction
Microsoft®VisualBasic®ScriptingEditionWriteMethod
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesto
Description
WritesaspecifiedstringtoaTextStreamfile.
Syntax
object.Write(string)
TheWritemethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaTextStreamobject.string Required.Thetextyouwanttowritetothefile.
Remarks
Specifiedstringsarewrittentothefilewithnointerveningspacesorcharactersbetweeneachstring.UsetheWriteLinemethodtowriteanewlinecharacterorastringthatendswithanewlinecharacter.
ThefollowingexampleillustratesuseoftheWritemethod:
FunctionWriteToFileConstForReading=1,ForWriting=2Dimfso,fSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.OpenTextFile("c:\testfile.txt",ForWriting,True)f.Write"Helloworld!"
Setf=fso.OpenTextFile("c:\testfile.txt",ForReading)WriteToFile=f.ReadLineEndFunction
Microsoft®VisualBasic®ScriptingEdition
WriteBlankLinesMethod
ScriptingRun-TimeReferenceVersion2
SeeAlsoAppliesto
Description
WritesaspecifiednumberofnewlinecharacterstoaTextStreamfile.
Syntax
object.WriteBlankLines(lines)
TheWriteBlankLinesmethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaTextStreamobject.
lines Required.Numberofnewlinecharactersyouwanttowritetothefile.
Remarks
ThefollowingexampleillustratesuseoftheWriteBlankLinesmethod:
FunctionWriteBlankLinesToFileConstForReading=1,ForWriting=2Dimfso,fSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.OpenTextFile("c:\testfile.txt",ForWriting,True)f.WriteBlankLines2f.WriteLine"HelloWorld!"Setf=fso.OpenTextFile("c:\testfile.txt",ForReading)WriteBlankLinesToFile=f.ReadAll
EndFunction
Microsoft®VisualBasic®ScriptingEdition
WriteLineMethodScriptingRun-TimeReference
Version2
SeeAlsoAppliesto
Description
WritesaspecifiedstringandnewlinecharactertoaTextStreamfile.
Syntax
object.WriteLine([string])
TheWriteLinemethodsyntaxhastheseparts:
Part Descriptionobject Required.AlwaysthenameofaTextStreamobject.
string Optional.Thetextyouwanttowritetothefile.Ifomitted,anewlinecharacteriswrittentothefile.
Remarks
ThefollowingexampleillustratesuseoftheWriteLinemethod:
FunctionWriteLineToFileConstForReading=1,ForWriting=2Dimfso,fSetfso=CreateObject("Scripting.FileSystemObject")Setf=fso.OpenTextFile("c:\testfile.txt",ForWriting,True)f.WriteLine"Helloworld!"f.WriteLine"VBScriptisfun!"Setf=fso.OpenTextFile("c:\testfile.txt",ForReading)WriteLineToFile=f.ReadAllEndFunction
Copyright
Microsoft®VisualBasic®ScriptingEdition
Informationinthisdocumentissubjecttochangewithoutnotice.Thenamesofcompanies,products,people,characters,and/ordatamentionedhereinarefictitiousandareinnowayintendedtorepresentanyrealindividual,company,product,orevent,unlessotherwisenoted.Complyingwithallapplicablecopyrightlawsistheresponsibilityoftheuser.Nopartofthisdocumentmaybereproducedortransmittedinanyformorbyanymeans,electronicormechanical,foranypurpose,withouttheexpresswrittenpermissionofMicrosoftCorporation.
Microsoftmayhavepatents,patentapplications,trademarks,copyrights,orotherintellectualpropertyrightscoveringsubjectmatterinthisdocument.ExceptasexpresslyprovidedinanywrittenlicenseagreementfromMicrosoft,thefurnishingofthisdocumentdoesnotgiveyouanylicensetothesepatents,trademarks,copyrights,orotherintellectualproperty.
©1991-1999MicrosoftCorporation.Allrightsreserved.
Microsoft,MS,MS-DOS,ActiveX,JScript,MicrosoftPress,VisualBasic,Windows,WindowsNT,Win32,andWin32sareeitherregisteredtrademarksortrademarksofMicrosoftCorporationintheU.S.A.and/orothercountries.
Otherproductandcompanynamesmentionedhereinmaybethetrademarksoftheirrespectiveowners.
Microsoft®VisualBasic®ScriptingEdition
InStrRevFunctionLanguageReference
Version2
SeeAlso
Description
Returnsthepositionofanoccurrenceofonestringwithinanother,fromtheendofstring.
Syntax
InStrRev(string1,string2[,start[,compare]])
TheInStrRevfunctionsyntaxhastheseparts:
Part Descriptionstring1 Required.Stringexpressionbeingsearched.string2 Required.Stringexpressionbeingsearchedfor.
start
Optional.Numericexpressionthatsetsthestartingpositionforeachsearch.Ifomitted,-1isused,whichmeansthatthesearchbeginsatthelastcharacterposition.IfstartcontainsNull,anerroroccurs.
compare
Optional.Numericvalueindicatingthekindofcomparisontousewhenevaluatingsubstrings.Ifomitted,abinarycomparisonisperformed.SeeSettingssectionforvalues.
Settings
Thecompareargumentcanhavethefollowingvalues:
Constant Value DescriptionvbBinaryCompare 0 Performabinarycomparison.vbTextCompare 1 Performatextualcomparison.
ReturnValues
InStrRevreturnsthefollowingvalues:
If InStrRevreturnsstring1iszero-length 0string1isNull Nullstring2iszero-length startstring2isNull Nullstring2isnotfound 0string2isfoundwithinstring1 Positionatwhichmatchisfoundstart>Len(string2) 0
Remarks
ThefollowingexamplesusetheInStrRevfunctiontosearchastring:
DimSearchString,SearchChar,MyPosSearchString="XXpXXpXXPXXP" 'Stringtosearchin.SearchChar="P" 'Searchfor"P".MyPos=InstrRev(SearchString,SearchChar,10,0) 'Abinarycomparisonstartingat 'position10.Returns9.MyPos=InstrRev(SearchString,SearchChar,-1,1) 'Atextualcomparisonstartingat 'thelastposition.Returns12.MyPos=InstrRev(SearchString,SearchChar,8) 'Comparisonisbinarybydefault(last 'argumentisomitted).Returns0.
NoteThesyntaxfortheInStrRevfunctionisnotthesameasthesyntaxfortheInStrfunction.
Microsoft®VisualBasic®ScriptingEditionAbsFunctionSeeAlso
LanguageReference
SgnFunction
Microsoft®VisualBasic®ScriptingEdition
VBScriptGlossary LanguageReference
ActiveXcontrol
Anobjectthatyouplaceonaformtoenableorenhanceauser'sinteractionwithanapplication.ActiveXcontrolshaveeventsandcanbeincorporatedintoothercontrols.Thecontrolshavean.ocxfilenameextension.
ActiveXobjectAnobjectthatisexposedtootherapplicationsorprogrammingtoolsthroughAutomationinterfaces.
argumentAconstant,variable,orexpressionpassedtoaprocedure.
arrayAsetofsequentiallyindexedelementshavingthesametypeofdata.Eachelementofanarrayhasauniqueidentifyingindexnumber.Changesmadetooneelementofanarraydonotaffecttheotherelements.
ASCIICharacterSetAmericanStandardCodeforInformationInterchange(ASCII)7-bitcharactersetwidelyusedtorepresentlettersandsymbolsfoundonastandardU.S.keyboard.TheASCIIcharactersetisthesameasthefirst128characters(0–127)intheANSIcharacterset.
AutomationobjectAnobjectthatisexposedtootherapplicationsorprogrammingtoolsthroughAutomationinterfaces.
bitwisecomparisonAbit-by-bitcomparisonofidenticallypositionedbitsintwonumericexpressions.
BooleanexpressionAnexpressionthatevaluatestoeitherTrueorFalse.
byreferenceAwayofpassingtheaddress,ratherthanthevalue,ofanargumenttoaprocedure.Thisallowstheproceduretoaccesstheactualvariable.Asaresult,thevariable'sactualvaluecanbechangedbytheproceduretowhichitispassed.
byvalueAwayofpassingthevalue,ratherthantheaddress,ofanargumenttoaprocedure.Thisallowstheproceduretoaccessacopyofthevariable.Asaresult,thevariable'sactualvaluecan'tbechangedbytheproceduretowhichitispassed.
charactercodeAnumberthatrepresentsaparticularcharacterinaset,suchastheASCIIcharacterset.
classTheformaldefinitionofanobject.Theclassactsasthetemplatefromwhichaninstanceofanobjectiscreatedatruntime.Theclassdefinesthepropertiesoftheobjectandthemethodsusedtocontroltheobject'sbehavior.
classmoduleAmodulecontainingthedefinitionofaclass(itspropertyandmethoddefinitions).
collectionAnobjectthatcontainsasetofrelatedobjects.Anobject'spositioninthecollectioncanchangewheneverachangeoccursinthecollection;therefore,thepositionofanyspecificobjectinthecollectionmayvary.
commentTextaddedtocodebyaprogrammerthatexplainshowthecodeworks.InVisualBasicScriptingEdition,acommentlinegenerallystartswithanapostrophe('),oryoucanusethekeywordRemfollowedbyaspace.
comparisonoperatorAcharacterorsymbolindicatingarelationshipbetweentwoormorevaluesorexpressions.Theseoperatorsincludelessthan(<),lessthanorequalto(<=),greaterthan(>),greaterthanorequalto(>=),notequal(<>),andequal(=).
Isisalsoacomparisonoperator,butitisusedexclusivelyfordeterminingifoneobjectreferenceisthesameasanother.
constantAnameditemthatretainsaconstantvaluethroughouttheexecutionofaprogram.Constantscanbeusedanywhereinyourcodeinplaceofactualvalues.Aconstantcanbeastringornumericliteral,anotherconstant,oranycombinationthatincludesarithmeticorlogicaloperatorsexceptIsandexponentiation.Forexample:
ConstA="MyString"
datarangesEachVariantsubtypehasaspecificrangeofallowedvalues:
Subtype RangeByte 0to255.Boolean TrueorFalse.Integer -32,768to32,767.Long -2,147,483,648to2,147,483,647.
Single -3.402823E38to-1.401298E-45fornegativevalues;1.401298E-45to3.402823E38forpositivevalues.
Double-1.79769313486232E308to-4.94065645841247E-324fornegativevalues;4.94065645841247E-324to1.79769313486232E308forpositivevalues.
Currency -922,337,203,685,477.5808to922,337,203,685,477.5807.Date January1,100toDecember31,9999,inclusive.Object AnyObjectreference.
String Variable-lengthstringsmayrangeinlengthfrom0toapproximately2billioncharacters.
dateexpressionAnyexpressionthatcanbeinterpretedasadate.Thisincludesanycombinationofdateliterals,numbersthatlooklikedates,stringsthatlooklikedates,anddatesreturnedfromfunctions.Adateexpressionislimitedtonumbersorstrings,inanycombination,thatcanrepresentadatefromJanuary1,100throughDecember31,9999.
Datesarestoredaspartofarealnumber.Valuestotheleftofthedecimalrepresentthedate;valuestotherightofthedecimalrepresentthetime.NegativenumbersrepresentdatespriortoDecember30,1899.
dateliteralAnysequenceofcharacterswithavalidformatthatissurroundedbynumbersigns(#).Validformatsincludethedateformatspecifiedbythelocalesettingsforyourcodeortheuniversaldateformat.Forexample,#12/31/99#isthedateliteralthatrepresentsDecember31,1999,whereEnglish-U.S.isthelocalesettingforyourapplication.
VBScriptalwaysinterpretsadateliteralasUS-ENGLISHifitispossibletodoso.Ifadateliteralcannotbeinterpretedasadate,anerroroccurs.
dateseparatorsCharactersusedtoseparatetheday,month,andyearwhendatevaluesareformatted.
EmptyAvaluethatindicatesthatnobeginningvaluehasbeenassignedtoavariable.Emptyvariablesare0inanumericcontext,orzero-lengthinastringcontext.
errornumberAwholenumberintherange0to65,535,inclusive,thatcorrespondstotheNumberpropertyoftheErrobject.WhencombinedwiththeNamepropertyoftheErrobject,thisnumberrepresentsaparticularerrormessage.
expression
Acombinationofkeywords,operators,variables,andconstantsthatyieldastring,number,orobject.Anexpressioncanperformacalculation,manipulatecharacters,ortestdata.
intrinsicconstantAconstantprovidedbyanapplication.Becauseyoucan'tdisableintrinsicconstants,youcan'tcreateauser-definedconstantwiththesamename.
keywordAwordorsymbolrecognizedaspartoftheVBScriptlanguage;forexample,astatement,functionname,oroperator.
localeThesetofinformationthatcorrespondstoagivenlanguageandcountry/region.Alocaleaffectsthelanguageofpredefinedprogrammingtermsandlocale-specificsettings.Therearetwocontextswherelocaleinformationisimportant:
Thecodelocaleaffectsthelanguageoftermssuchaskeywordsanddefineslocale-specificsettingssuchasthedecimalandlistseparators,dateformats,andcharactersortingorder.
Thesystemlocaleaffectsthewaylocale-awarefunctionalitybehaves,forexample,whenyoudisplaynumbersorconvertstringstodates.YousetthesystemlocaleusingtheControlPanelutilitiesprovidedbytheoperatingsystem.
NothingThespecialvaluethatindicatesthatanobjectvariableisnolongerassociatedwithanyactualobject.
NullAvalueindicatingthatavariablecontainsnovaliddata.Nullistheresultof:
AnexplicitassignmentofNulltoavariable.
AnyoperationbetweenexpressionsthatcontainNull.
numericexpressionAnyexpressionthatcanbeevaluatedasanumber.Elementsoftheexpressioncanincludeanycombinationofkeywords,variables,constants,andoperatorsthatresultinanumber.
objecttypeAtypeofobjectexposedbyanapplication,forexample,Application,File,Range,andSheet.Refertotheapplication'sdocumentation(MicrosoftExcel,MicrosoftProject,MicrosoftWord,andsoon)foracompletelistingofavailableobjects.
piPiisamathematicalconstantequaltoapproximately3.1415926535897932.
PrivateVariablesthatarevisibleonlytothescriptinwhichtheyaredeclared.
procedureAnamedsequenceofstatementsexecutedasaunit.Forexample,FunctionandSubaretypesofprocedures.
procedurelevelDescribesstatementslocatedwithinaFunctionorSubprocedure.Declarationsareusuallylistedfirst,followedbyassignmentsandotherexecutablecode.Forexample:
SubMySub()'Thisstatementdeclaresasubprocedureblock.DimA'Thisstatementstartstheprocedureblock.A="Myvariable"'Procedure-levelcode.Debug.PrintA'Procedure-levelcode.EndSub'Thisstatementendsasubprocedureblock.
Notethatscript-levelcoderesidesoutsideanyprocedureblocks.
propertyAnamedattributeofanobject.Propertiesdefineobjectcharacteristicssuchassize,color,andscreenlocation,orthestateofanobject,suchasenabledordisabled.
PublicVariablesdeclaredusingthePublicStatementarevisibletoallproceduresinallmodulesinallapplications.
runtimeThetimewhencodeisrunning.Duringruntime,youcan'teditthecode.
run-timeerrorAnerrorthatoccurswhencodeisrunning.Arun-timeerrorresultswhenastatementattemptsaninvalidoperation.
scopeDefinesthevisibilityofavariable,procedure,orobject.Forexample,avariabledeclaredasPublicisvisibletoallproceduresinallmodules.Variablesdeclaredinproceduresarevisibleonlywithintheprocedureandlosetheirvaluebetweencalls.
SCODEAlongintegervaluethatisusedtopassdetailedinformationtothecallerofaninterfacememberorAPIfunction.ThestatuscodesforOLEinterfacesandAPIsaredefinedinFACILITY_ITF.
scriptlevelAnycodeoutsideaprocedureisreferredtoasscript-levelcode.
seedAninitialvalueusedtogeneratepseudorandomnumbers.Forexample,theRandomizestatementcreatesaseednumberusedbytheRndfunctiontocreateuniquepseudorandomnumbersequences.
stringcomparisonAcomparisonoftwosequencesofcharacters.Unlessspecifiedinthefunctionmakingthecomparison,allstringcomparisonsarebinary.InEnglish,binarycomparisonsarecase-sensitive;textcomparisonsarenot.
stringexpressionAnyexpressionthatevaluatestoasequenceofcontiguouscharacters.Elementsofastringexpressioncanincludeafunctionthatreturnsastring,astringliteral,astringconstant,orastringvariable.
typelibraryAfileorcomponentwithinanotherfilethatcontainsstandarddescriptionsofexposedobjects,properties,andmethods.
variableAnamedstoragelocationthatcancontaindatathatcanbemodifiedduringprogramexecution.Eachvariablehasanamethatuniquelyidentifiesitwithinitslevelofscope.
Variablenames:
Mustbeginwithanalphabeticcharacter.
Can'tcontainanembeddedperiodortype-declarationcharacter.
Mustbeuniquewithinthesamescope.
Mustbenolongerthan255characters.
Microsoft®VisualBasic®ScriptingEdition+OperatorSeeAlso
ScriptingRun-TimeReference
&Operator-OperatorArithmeticOperatorsConcatenationOperatorsOperatorPrecedenceOperatorSummary
Microsoft®VisualBasic®ScriptingEditionAndOperatorSeeAlso
LanguageReference
LogicalOperatorsNotOperatorOperatorPrecedenceOperatorSummaryOrOperatorXorOperator
Microsoft®VisualBasic®ScriptingEditionArrayFunctionSeeAlso
LanguageReference
DimStatement
Microsoft®VisualBasic®ScriptingEditionAscFunctionSeeAlso
LanguageReference
ChrFunction
Microsoft®VisualBasic®ScriptingEdition=OperatorSeeAlso
LanguageReference
ComparisonOperatorsOperatorPrecedenceOperatorSummarySetStatement
Microsoft®VisualBasic®ScriptingEditionAtnFunctionSeeAlso
LanguageReference
CosFunctionDerivedMathFunctionsSinFunctionTanFunction
Microsoft®VisualBasic®ScriptingEditionCBoolFunctionSeeAlso
LanguageReference
CByteFunctionCCurFunctionCDateFunctionCDblFunctionCIntFunctionCLngFunctionCSngFunctionCStrFunction
Microsoft®VisualBasic®ScriptingEditionCByteFunctionSeeAlso
LanguageReference
CBoolFunctionCCurFunctionCDateFunctionCDblFunctionCIntFunctionCLngFunctionCSngFunctionCStrFunction
Microsoft®VisualBasic®ScriptingEditionCCurFunctionSeeAlso
LanguageReference
CBoolFunctionCByteFunctionCDateFunctionCDblFunctionCIntFunctionCLngFunctionCSngFunctionCStrFunction
Microsoft®VisualBasic®ScriptingEditionCDateFunctionSeeAlso
LanguageReference
IsDateFunction
Microsoft®VisualBasic®ScriptingEditionCDblFunctionSeeAlso
LanguageReference
CBoolFunctionCByteFunctionCCurFunctionCDateFunctionCIntFunctionCLngFunctionCSngFunctionCStrFunction
Microsoft®VisualBasic®ScriptingEditionChrFunctionSeeAlso
LanguageReference
AscFunction
Microsoft®VisualBasic®ScriptingEditionCIntFunctionSeeAlso
LanguageReference
CBoolFunctionCByteFunctionCCurFunctionCDateFunctionCDblFunctionCLngFunctionCSngFunctionCStrFunctionInt,FixFunctions
Microsoft®VisualBasic®ScriptingEditionVersionInformation
LanguageReference
ThefollowingtableliststheversionofMicrosoftVisualBasicScriptingEditionimplementedbyhostapplications.
HostApplicationVBScriptVersion1.0 2.0 3.0 4.0 5.0
MicrosoftInternetExplorer3.0 x MicrosoftInternetInformationServer3.0 x MicrosoftInternetExplorer4.0 x MicrosoftInternetInformationServer4.0 x MicrosoftWindowsScriptingHost1.0 x MicrosoftOutlook98 x MicrosoftVisualStudio6.0 x MicrosoftInternetExplorer5.0 xMicrosoftInternetInformationServices5.0 x
ThefollowingtablelistsVBScriptlanguagefeaturesandtheversionwhenfirstintroduced.
LanguageElementVersionFirstIntroduced
1.0 2.0 3.0 4.0 5.0AbsFunction x AdditionOperator(+) x AndOperator x ArrayFunction x AscFunction x
AssignmentOperator(=) x AtnFunction x CallStatement x CBoolFunction x CByteFunction x CCurFunction x CDateFunction x CDblFunction x ChrFunction x CIntFunction x ClassObject xClassStatement xClearMethod x CLngFunction x ColorConstants x ComparisonConstants x ConcatenationOperator(&) x ConstStatement x CosFunction x CreateObjectFunction x CSngFunction x CStrFunction x DateandTimeConstants x DateFormatConstants x DateFunction x DateAddFunction x DateDiffFunction x DatePartFunction x DateSerialFunction x DateValueFunction x
DayFunction x
DescriptionProperty x DimStatement x DivisionOperator(/) x Do...LoopStatement x Empty x EqvOperator x EraseStatement x ErrObject x EvalFunction xExecuteMethod xExecuteStatement xExecuteGlobalStatement xExitStatement x ExpFunction x ExponentiationOperator(^) x False x FilterFunction x FirstIndexProperty xFixFunction x For...NextStatement x ForEach...NextStatement x FormatCurrencyFunction x FormatDateTimeFunction x FormatNumberFunction x FormatPercentFunction x FunctionStatement x GetLocaleFunction xGetObjectFunction x
GetRefFunction xGlobalProperty x
HexFunction x HelpContextProperty x HelpFileProperty x HourFunction x If...Then...ElseStatement x IgnoreCaseProperty xImpOperator x InitializeEvent xInputBoxFunction x InStrFunction x InStrRevFunction x IntFunction x IntegerDivisionOperator(\) x IsOperator x IsArrayFunction x IsDateFunction x IsEmptyFunction x IsNullFunction x IsNumericFunction x IsObjectFunction x JoinFunction x LBoundFunction x LCaseFunction x LeftFunction x LenFunction x LengthProperty xLoadPictureFunction x
LogFunction x LTrimFunction x MatchObject x
MatchesCollection xMidFunction x MinuteFunction x MiscellaneousConstants x ModOperator x MonthFunction x MonthNameFunction x MsgBoxConstants x MsgBoxFunction x MultiplicationOperator(*) x NegationOperator(-) x NotOperator x NowFunction x Nothing x Null x NumberProperty x OctFunction x OnErrorStatement x OptionExplicitStatement x OrOperator x PatternProperty xPrivateStatement x PropertyGetStatement xPropertyLetStatement xPropertySetStatement xPublicStatement x
RaiseMethod x RandomizeStatement x ReDimStatement x RegExpObject x
RemStatement x ReplaceFunction x ReplaceMethod xRGBFunction x RightFunction x RndFunction x RoundFunction x RTrimFunction x ScriptEngineFunction x ScriptEngineBuildVersionFunction x
ScriptEngineMajorVersionFunction x
ScriptEngineMinorVersionFunction x
SecondFunction x SelectCaseStatement x SetStatement x SetLocaleFunction xSgnFunction x SinFunction x SourceProperty x SpaceFunction x SplitFunction x SqrFunction x StrCompFunction x
StringConstants x StringFunction x StrReverseFunction x SubStatement x SubtractionOperator(-) x TanFunction x TerminateEvent xTestMethod xTimeFunction x TimerFunction xTimeSerialFunction x TimeValueFunction x TrimFunction x TristateConstants x True x TypeNameFunction x UBoundFunction x UCaseFunction x ValueProperty xVarTypeConstants x VarTypeFunction x VBScriptConstants x WeekdayFunction x WeekdayNameFunction x While...WendStatement x WithStatement xXorOperator x YearFunction x
Microsoft®VisualBasic®ScriptingEditionClassObjectSeeAlso
LanguageReference
ClassStatementDimStatementSetStatement
Microsoft®VisualBasic®ScriptingEditionClassObjectEvents
LanguageReference
InitializeEventTerminateEvent
Microsoft®VisualBasic®ScriptingEditionClassStatementSeeAlso
LanguageReference
DimStatementFunctionStatementPrivateStatementPropertyGetStatementPropertyLetStatementPropertySetStatementPublicStatementSetStatementSubStatement
Microsoft®VisualBasic®ScriptingEditionClearMethodSeeAlso
LanguageReference
DescriptionPropertyErrObjectNumberPropertyOnErrorStatementRaiseMethodSourceProperty
Microsoft®VisualBasic®ScriptingEditionClearMethodAppliesTo
LanguageReference
ErrObject
Microsoft®VisualBasic®ScriptingEditionCLngFunctionSeeAlso
LanguageReference
CBoolFunctionCByteFunctionCCurFunctionCDateFunctionCDblFunctionCIntFunctionCSngFunctionCStrFunctionInt,FixFunctions
Microsoft®VisualBasic®ScriptingEdition
ComparisonConstantsSeeAlso
LanguageReference
ColorConstantsDateandTimeConstantsDateFormatConstantsMiscellaneousConstantsMsgBoxConstantsStringConstantsTristateConstantsVarTypeConstants
Microsoft®VisualBasic®ScriptingEdition&OperatorSeeAlso
LanguageReference
ConcatenationOperatorsOperatorPrecedenceOperatorSummary
Microsoft®VisualBasic®ScriptingEditionConstStatementSeeAlso
LanguageReference
DimStatementFunctionStatementPrivateStatementPublicStatementSubStatement
Microsoft®VisualBasic®ScriptingEditionCosFunctionSeeAlso
LanguageReference
AtnFunctionDerivedMathFunctionsSinFunctionTanFunction
Microsoft®VisualBasic®ScriptingEdition
CreateObjectFunctionSeeAlso
LanguageReference
GetObjectFunction
Microsoft®VisualBasic®ScriptingEditionCSngFunctionSeeAlso
LanguageReference
CBoolFunctionCByteFunctionCCurFunctionCDateFunctionCDblFunctionCIntFunctionCLngFunctionCStrFunction
Microsoft®VisualBasic®ScriptingEditionCStrFunctionSeeAlso
LanguageReference
CBoolFunctionCByteFunctionCCurFunctionCDateFunctionCDblFunctionCIntFunctionCLngFunctionCSngFunction
Microsoft®VisualBasic®ScriptingEditionDateandTimeConstantsSeeAlso
LanguageReference
ColorConstantsComparisonConstantsDateFormatConstantsMiscellaneousConstantsMsgBoxConstantsStringConstantsTristateConstantsVarTypeConstants
Microsoft®VisualBasic®ScriptingEditionDateFormatConstantsSeeAlso
LanguageReference
ColorConstantsComparisonConstantsDateandTimeConstantsMiscellaneousConstantsMsgBoxConstantsStringConstantsTristateConstantsVarTypeConstants
Microsoft®VisualBasic®ScriptingEditionDateFunctionSeeAlso
LanguageReference
CDateFunctionNowFunctionTimeFunction
Microsoft®VisualBasic®ScriptingEdition
DateAddFunctionSeeAlso
LanguageReference
DateDiffFunctionDatePartFunction
Microsoft®VisualBasic®ScriptingEdition
DateDiffFunctionSeeAlso
LanguageReference
DateAddFunctionDatePartFunction
Microsoft®VisualBasic®ScriptingEdition
DatePartFunctionSeeAlso
LanguageReference
DateAddFunctionDateDiffFunction
Microsoft®VisualBasic®ScriptingEdition
DateSerialFunctionSeeAlso
LanguageReference
DateFunctionDateValueFunctionDayFunctionMonthFunctionNowFunctionTimeSerialFunctionTimeValueFunctionWeekdayFunctionYearFunction
Microsoft®VisualBasic®ScriptingEdition
DateValueFunctionSeeAlso
LanguageReference
CDateFunctionDateSerialFunctionDayFunctionMonthFunctionNowFunctionTimeSerialFunctionTimeValueFunctionWeekdayFunctionYearFunction
Microsoft®VisualBasic®ScriptingEditionDayFunctionSeeAlso
LanguageReference
DateFunctionHourFunctionMinuteFunctionMonthFunctionNowFunctionSecondFunctionWeekdayFunctionYearFunction
Microsoft®VisualBasic®ScriptingEdition
DescriptionPropertyAppliesTo
LanguageReference
ErrObject
Microsoft®VisualBasic®ScriptingEditionDimStatementSeeAlso
LanguageReference
PrivateStatementPublicStatementReDimStatementSetStatement
Microsoft®VisualBasic®ScriptingEdition/OperatorSeeAlso
LanguageReference
*Operator\OperatorArithmeticOperatorsOperatorPrecedenceOperatorSummary
Microsoft®VisualBasic®ScriptingEdition
Do...LoopStatementSeeAlso
LanguageReference
ExitStatementFor...NextStatementWhile...WendStatement
Microsoft®VisualBasic®ScriptingEditionEqvOperatorSeeAlso
LanguageReference
ImpOperatorLogicalOperatorsOperatorPrecedenceOperatorSummary
Microsoft®VisualBasic®ScriptingEditionEraseStatementSeeAlso
LanguageReference
DimStatementNothingReDimStatement
Microsoft®VisualBasic®ScriptingEditionErrObjectSeeAlso
LanguageReference
ErrorMessagesOnErrorStatement
Microsoft®VisualBasic®ScriptingEditionErrObjectProperties
LanguageReference
DescriptionPropertyHelpContextPropertyHelpFilePropertyNumberPropertySourceProperty
Microsoft®VisualBasic®ScriptingEditionErrObjectMethods
LanguageReference
ClearMethodRaiseMethod
Microsoft®VisualBasic®ScriptingEditionEvalFunctionSeeAlso
LanguageReference
ExecuteStatement
Microsoft®VisualBasic®ScriptingEditionExecuteMethodSeeAlso
LanguageReference
ReplaceMethodTestMethod
Microsoft®VisualBasic®ScriptingEditionExecuteMethodAppliesTo
LanguageReference
RegExpObject
Microsoft®VisualBasic®ScriptingEditionExecuteStatementSeeAlso
LanguageReference
EvalFunctionExecuteGlobalStatement
Microsoft®VisualBasic®ScriptingEditionExitStatementSeeAlso
LanguageReference
Do...LoopStatementForEach...NextStatementFor...NextStatementFunctionStatementSubStatement
Microsoft®VisualBasic®ScriptingEditionExpFunctionSeeAlso
LanguageReference
DerivedMathFunctionsLogFunction
Microsoft®VisualBasic®ScriptingEdition^OperatorSeeAlso
LanguageReference
ArithmeticOperatorsOperatorPrecedenceOperatorSummary
Microsoft®VisualBasic®ScriptingEditionFilterFunctionSeeAlso
LanguageReference
ReplaceFunction
Microsoft®VisualBasic®ScriptingEdition
FirstIndexPropertySeeAlso
LanguageReference
LengthPropertyValueProperty
Microsoft®VisualBasic®ScriptingEdition
FirstIndexPropertyAppliesTo
LanguageReference
MatchObject
Microsoft®VisualBasic®ScriptingEditionInt,FixFunctionsSeeAlso
LanguageReference
CIntFunctionRoundFunction
Microsoft®VisualBasic®ScriptingEdition
For...NextStatementSeeAlso
LanguageReference
Do...LoopStatementExitStatementForEach...NextStatementWhile...WendStatement
Microsoft®VisualBasic®ScriptingEditionForEach...NextStatementSeeAlso
LanguageReference
Do...LoopStatementExitStatementFor...NextStatementWhile...WendStatement
Microsoft®VisualBasic®ScriptingEdition
FormatCurrencyFunctionSeeAlso
LanguageReference
FormatDateTimeFunctionFormatNumberFunctionFormatPercentFunction
Microsoft®VisualBasic®ScriptingEdition
FormatDateTimeFunctionSeeAlso
LanguageReference
FormatCurrencyFunctionFormatNumberFunctionFormatPercentFunction
Microsoft®VisualBasic®ScriptingEdition
FormatNumberFunctionSeeAlso
LanguageReference
FormatCurrencyFunctionFormatDateTimeFunctionFormatPercentFunction
Microsoft®VisualBasic®ScriptingEdition
FormatPercentFunctionSeeAlso
LanguageReference
FormatCurrencyFunctionFormatDateTimeFunctionFormatNumberFunction
Microsoft®VisualBasic®ScriptingEdition
FunctionStatementSeeAlso
LanguageReference
CallStatementDimStatementExitStatementNothingSetStatementSubStatement
Microsoft®VisualBasic®ScriptingEdition
GetObjectFunctionSeeAlso
LanguageReference
CreateObjectFunction
Microsoft®VisualBasic®ScriptingEditionGetRefFunctionSeeAlso
LanguageReference
FunctionStatementSetStatementSubStatement
Microsoft®VisualBasic®ScriptingEditionGlobalPropertySeeAlso
LanguageReference
IgnoreCasePropertyPatternProperty
Microsoft®VisualBasic®ScriptingEditionGlobalPropertyAppliesTo
LanguageReference
RegExpObject
Microsoft®VisualBasic®ScriptingEditionHexFunctionSeeAlso
LanguageReference
OctFunction
Microsoft®VisualBasic®ScriptingEdition
HelpContextPropertySeeAlso
LanguageReference
DescriptionPropertyHelpFilePropertyNumberPropertySourceProperty
Microsoft®VisualBasic®ScriptingEdition
HelpContextPropertyAppliesTo
LanguageReference
ErrObject
Microsoft®VisualBasic®ScriptingEdition
HelpFilePropertySeeAlso
LanguageReference
DescriptionPropertyHelpContextPropertyNumberPropertySourceProperty
Microsoft®VisualBasic®ScriptingEdition
HelpFilePropertyAppliesTo
LanguageReference
ErrObject
Microsoft®VisualBasic®ScriptingEditionHourFunctionSeeAlso
LanguageReference
DayFunctionMinuteFunctionNowFunctionSecondFunctionTimeFunction
Microsoft®VisualBasic®ScriptingEdition
IgnoreCasePropertySeeAlso
LanguageReference
GlobalPropertyPatternProperty
Microsoft®VisualBasic®ScriptingEdition
IgnoreCasePropertyAppliesTo
LanguageReference
RegExpObject
Microsoft®VisualBasic®ScriptingEditionImpOperatorSeeAlso
LanguageReference
EqvOperatorLogicalOperatorsOperatorPrecedenceOperatorSummary
Microsoft®VisualBasic®ScriptingEdition
InitializeEventSeeAlso
LanguageReference
ClassObjectClassStatementTerminateEvent
Microsoft®VisualBasic®ScriptingEdition
InitializeEventAppliesTo
LanguageReference
ClassObject
Microsoft®VisualBasic®ScriptingEdition
InputBoxFunctionSeeAlso
LanguageReference
MsgBoxFunction
Microsoft®VisualBasic®ScriptingEditionInStrFunctionSeeAlso
LanguageReference
InStrRevFunction
Microsoft®VisualBasic®ScriptingEdition\OperatorSeeAlso
LanguageReference
*Operator/OperatorArithmeticOperatorsOperatorPrecedenceOperatorSummary
Microsoft®VisualBasic®ScriptingEditionIsOperatorSeeAlso
LanguageReference
ComparisonOperatorsOperatorPrecedenceOperatorSummary
Microsoft®VisualBasic®ScriptingEditionIsArrayFunctionSeeAlso
LanguageReference
IsDateFunctionIsEmptyFunctionIsNullFunctionIsNumericFunctionIsObjectFunctionVarTypeFunction
Microsoft®VisualBasic®ScriptingEditionIsDateFunctionSeeAlso
LanguageReference
CDateFunctionIsArrayFunctionIsEmptyFunctionIsNullFunctionIsNumericFunctionIsObjectFunctionVarTypeFunction
Microsoft®VisualBasic®ScriptingEdition
IsEmptyFunctionSeeAlso
LanguageReference
IsArrayFunctionIsDateFunctionIsNullFunctionIsNumericFunctionIsObjectFunctionVarTypeFunction
Microsoft®VisualBasic®ScriptingEditionIsNullFunctionSeeAlso
LanguageReference
IsArrayFunctionIsDateFunctionIsEmptyFunctionIsNumericFunctionIsObjectFunctionVarTypeFunction
Microsoft®VisualBasic®ScriptingEdition
IsNumericFunctionSeeAlso
LanguageReference
IsArrayFunctionIsDateFunctionIsEmptyFunctionIsNullFunctionIsObjectFunctionVarTypeFunction
Microsoft®VisualBasic®ScriptingEdition
IsObjectFunctionSeeAlso
LanguageReference
IsArrayFunctionIsDateFunctionIsEmptyFunctionIsNullFunctionIsNumericFunctionSetStatementVarTypeFunction
Microsoft®VisualBasic®ScriptingEditionJoinFunctionSeeAlso
LanguageReference
SplitFunction
Microsoft®VisualBasic®ScriptingEditionLBoundFunctionSeeAlso
LanguageReference
DimStatementReDimStatementUBoundFunction
Microsoft®VisualBasic®ScriptingEditionLCaseFunctionSeeAlso
LanguageReference
UCaseFunction
Microsoft®VisualBasic®ScriptingEditionLeftFunctionSeeAlso
LanguageReference
LenFunctionMidFunctionRightFunction
Microsoft®VisualBasic®ScriptingEditionLenFunctionSeeAlso
LanguageReference
InStrFunction
Microsoft®VisualBasic®ScriptingEditionLengthPropertySeeAlso
LanguageReference
FirstIndexPropertyValueProperty
Microsoft®VisualBasic®ScriptingEditionLengthPropertyAppliesTo
LanguageReference
MatchObject
Microsoft®VisualBasic®ScriptingEditionLogFunctionSeeAlso
LanguageReference
DerivedMathFunctionsExpFunction
Microsoft®VisualBasic®ScriptingEditionLTrim,RTrim,andTrimFunctionsSeeAlso
LanguageReference
LeftFunctionRightFunction
Microsoft®VisualBasic®ScriptingEditionMatchObjectSeeAlso
LanguageReference
MatchesCollectionRegExpObject
Microsoft®VisualBasic®ScriptingEditionMatchObjectProperties
LanguageReference
FirstIndexPropertyLengthPropertyValueProperty
Microsoft®VisualBasic®ScriptingEditionMatchesCollectionSeeAlso
LanguageReference
ForEach...NextStatementMatchObjectRegExpObject
Microsoft®VisualBasic®ScriptingEditionMatchesCollectionProperties
LanguageReference
CountPropertyItemProperty
Microsoft®VisualBasic®ScriptingEditionMidFunctionSeeAlso
LanguageReference
LeftFunctionLenFunctionLTrim,RTrim,andTrimFunctionsRightFunction
Microsoft®VisualBasic®ScriptingEditionMinuteFunctionSeeAlso
LanguageReference
DayFunctionHourFunctionNowFunctionSecondFunctionTimeFunction
Microsoft®VisualBasic®ScriptingEdition
MiscellaneousConstantsSeeAlso
LanguageReference
ColorConstantsComparisonConstantsDateandTimeConstantsDateFormatConstantsMsgBoxConstantsStringConstantsTristateConstantsVarTypeConstants
Microsoft®VisualBasic®ScriptingEditionModOperatorSeeAlso
LanguageReference
ArithmeticOperatorsOperatorPrecedenceOperatorSummary
Microsoft®VisualBasic®ScriptingEditionMonthFunctionSeeAlso
LanguageReference
DateFunctionDayFunctionNowFunctionWeekdayFunctionYearFunction
Microsoft®VisualBasic®ScriptingEdition
MonthNameFunctionSeeAlso
LanguageReference
WeekdayNameFunction
Microsoft®VisualBasic®ScriptingEditionMsgBoxConstantsSeeAlso
LanguageReference
ColorConstantsComparisonConstantsDateandTimeConstantsDateFormatConstantsMiscellaneousConstantsStringConstantsTristateConstantsVarTypeConstants
Microsoft®VisualBasic®ScriptingEditionMsgBoxFunctionSeeAlso
LanguageReference
InputBoxFunction
Microsoft®VisualBasic®ScriptingEdition*OperatorSeeAlso
LanguageReference
\OperatorArithmeticOperatorsOperatorPrecedenceOperatorSummary
Microsoft®VisualBasic®ScriptingEdition-OperatorSeeAlso
LanguageReference
+OperatorArithmeticOperatorsOperatorPrecedenceOperatorSummary
Microsoft®VisualBasic®ScriptingEditionNotOperatorSeeAlso
LanguageReference
AndOperatorLogicalOperatorsOperatorPrecedenceOperatorSummaryOrOperatorXorOperator
Microsoft®VisualBasic®ScriptingEditionNowFunctionSeeAlso
LanguageReference
DateFunctionDayFunctionHourFunctionMinuteFunctionMonthFunctionSecondFunctionTimeFunctionWeekdayFunctionYearFunction
Microsoft®VisualBasic®ScriptingEditionNothingSeeAlso
LanguageReference
DimStatementSetStatement
Microsoft®VisualBasic®ScriptingEditionNumberPropertySeeAlso
LanguageReference
DescriptionPropertyHelpContextPropertyHelpFilePropertyErrObjectSourcePropertyErrorMessages
Microsoft®VisualBasic®ScriptingEditionNumberPropertyAppliesTo
LanguageReference
ErrObject
Microsoft®VisualBasic®ScriptingEditionOctFunctionSeeAlso
LanguageReference
HexFunction
Microsoft®VisualBasic®ScriptingEditionOnErrorStatementSeeAlso
LanguageReference
ErrObjectExitStatement
Microsoft®VisualBasic®ScriptingEdition
OperatorPrecedenceSeeAlso
LanguageReference
IsOperatorOperatorSummary
Microsoft®VisualBasic®ScriptingEditionOrOperatorSeeAlso
LanguageReference
AndOperatorLogicalOperatorsNotOperatorOperatorPrecedenceOperatorSummaryXorOperator
Microsoft®VisualBasic®ScriptingEditionPatternPropertySeeAlso
LanguageReference
GlobalPropertyIgnoreCaseProperty
Microsoft®VisualBasic®ScriptingEditionPatternPropertyAppliesTo
LanguageReference
RegExpObject
Microsoft®VisualBasic®ScriptingEditionPrivateStatementSeeAlso
LanguageReference
DimStatementPublicStatementReDimStatementSetStatement
Microsoft®VisualBasic®ScriptingEdition
PropertyGetStatementSeeAlso
LanguageReference
ClassStatementDimStatementExitStatementFunctionStatementPrivateStatementPropertyLetStatementPropertySetStatementPublicStatementSetStatementSubStatement
Microsoft®VisualBasic®ScriptingEdition
PropertyLetStatementSeeAlso
LanguageReference
ClassStatementDimStatementExitStatementFunctionStatementPrivateStatementPropertyGetStatementPropertySetStatementPublicStatementSetStatementSubStatement
Microsoft®VisualBasic®ScriptingEdition
PropertySetStatementSeeAlso
LanguageReference
ClassStatementDimStatementExitStatementFunctionStatementPrivateStatementPropertyGetStatementPropertyLetStatementPublicStatementSetStatementSubStatement
Microsoft®VisualBasic®ScriptingEditionPublicStatementSeeAlso
LanguageReference
DimStatementPrivateStatementReDimStatementSetStatement
Microsoft®VisualBasic®ScriptingEditionRaiseMethodSeeAlso
LanguageReference
ClearMethodDescriptionPropertyErrObjectNumberPropertySourceProperty
Microsoft®VisualBasic®ScriptingEditionRaiseMethodAppliesTo
LanguageReference
ErrObject
Microsoft®VisualBasic®ScriptingEdition
RandomizeStatementSeeAlso
LanguageReference
RndFunctionTimerFunction
Microsoft®VisualBasic®ScriptingEditionReDimStatementSeeAlso
LanguageReference
DimStatementSetStatement
Microsoft®VisualBasic®ScriptingEditionRegExpObjectSeeAlso
LanguageReference
MatchObjectMatchesCollection
Microsoft®VisualBasic®ScriptingEditionRegExpObjectMethods
LanguageReference
ExecuteMethodReplaceMethodTestMethod
Microsoft®VisualBasic®ScriptingEditionRegExpObjectProperties
LanguageReference
GlobalPropertyIgnoreCasePropertyPatternProperty
Microsoft®VisualBasic®ScriptingEditionReplaceFunctionSeeAlso
LanguageReference
FilterFunction
Microsoft®VisualBasic®ScriptingEditionReplaceMethodSeeAlso
LanguageReference
ExecuteMethodTestMethod
Microsoft®VisualBasic®ScriptingEditionReplaceMethodAppliesTo
LanguageReference
RegExpObject
Microsoft®VisualBasic®ScriptingEditionRightFunctionSeeAlso
LanguageReference
LeftFunctionLenFunctionMidFunction
Microsoft®VisualBasic®ScriptingEditionRndFunctionSeeAlso
LanguageReference
RandomizeStatement
Microsoft®VisualBasic®ScriptingEditionRoundFunctionSeeAlso
LanguageReference
Int,FixFunctions
Microsoft®VisualBasic®ScriptingEdition
ScriptEngineFunctionSeeAlso
LanguageReference
ScriptEngineBuildVersionFunctionScriptEngineMajorVersionFunctionScriptEngineMinorVersionFunction
Microsoft®VisualBasic®ScriptingEdition
ScriptEngineBuildVersionFunctionSeeAlso
LanguageReference
ScriptEngineFunctionScriptEngineMajorVersionFunctionScriptEngineMinorVersionFunction
Microsoft®VisualBasic®ScriptingEdition
ScriptEngineMajorVersionFunctionSeeAlso
LanguageReference
ScriptEngineFunctionScriptEngineBuildVersionFunctionScriptEngineMinorVersionFunction
Microsoft®VisualBasic®ScriptingEdition
ScriptEngineMinorVersionFunctionSeeAlso
LanguageReference
ScriptEngineFunctionScriptEngineBuildVersionFunctionScriptEngineMajorVersionFunction
Microsoft®VisualBasic®ScriptingEditionSecondFunctionSeeAlso
LanguageReference
DayFunctionHourFunctionMinuteFunctionNowFunctionTimeFunction
Microsoft®VisualBasic®ScriptingEditionSelectCaseStatementSeeAlso
LanguageReference
If...Then...ElseStatement
Microsoft®VisualBasic®ScriptingEditionSetStatementSeeAlso
LanguageReference
=OperatorDimStatementGetRefFunctionReDimStatement
Microsoft®VisualBasic®ScriptingEditionSgnFunctionSeeAlso
LanguageReference
AbsFunction
Microsoft®VisualBasic®ScriptingEditionSinFunctionSeeAlso
LanguageReference
AtnFunctionCosFunctionDerivedMathFunctionsTanFunction
Microsoft®VisualBasic®ScriptingEditionSourcePropertySeeAlso
LanguageReference
DescriptionPropertyErrObjectHelpContextPropertyHelpFilePropertyNumberPropertyOnErrorStatement
Microsoft®VisualBasic®ScriptingEditionSourcePropertyAppliesTo
LanguageReference
ErrObject
Microsoft®VisualBasic®ScriptingEditionSpaceFunctionSeeAlso
LanguageReference
StringFunction
Microsoft®VisualBasic®ScriptingEditionSplitFunctionSeeAlso
LanguageReference
JoinFunction
Microsoft®VisualBasic®ScriptingEditionStringConstantsSeeAlso
LanguageReference
ColorConstantsComparisonConstantsDateandTimeConstantsDateFormatConstantsMiscellaneousConstantsMsgBoxConstantsTristateConstantsVarTypeConstants
Microsoft®VisualBasic®ScriptingEditionStringFunctionSeeAlso
LanguageReference
SpaceFunction
Microsoft®VisualBasic®ScriptingEditionSubStatementSeeAlso
LanguageReference
CallStatementDimStatementExitStatementFunctionStatement
Microsoft®VisualBasic®ScriptingEditionTanFunctionSeeAlso
LanguageReference
AtnFunctionCosFunctionDerivedMathFunctionsSinFunction
Microsoft®VisualBasic®ScriptingEdition
TerminateEventSeeAlso
LanguageReference
ClassObjectClassStatementInitializeEvent
Microsoft®VisualBasic®ScriptingEdition
TerminateEventAppliesTo
LanguageReference
ClassObject
Microsoft®VisualBasic®ScriptingEditionTestMethodSeeAlso
LanguageReference
ExecuteMethodReplaceMethod
Microsoft®VisualBasic®ScriptingEditionTestMethodAppliesTo
LanguageReference
RegExpObject
Microsoft®VisualBasic®ScriptingEditionTimeFunctionSeeAlso
LanguageReference
DateFunction
Microsoft®VisualBasic®ScriptingEdition
TimerFunctionSeeAlso
LanguageReference
RandomizeStatement
Microsoft®VisualBasic®ScriptingEdition
TimeSerialFunctionSeeAlso
LanguageReference
DateSerialFunctionDateValueFunctionHourFunctionMinuteFunctionNowFunctionSecondFunctionTimeValueFunction
Microsoft®VisualBasic®ScriptingEdition
TimeValueFunctionSeeAlso
LanguageReference
DateSerialFunctionDateValueFunctionHourFunctionMinuteFunctionNowFunctionSecondFunctionTimeSerialFunction
Microsoft®VisualBasic®ScriptingEdition
TypeNameFunctionSeeAlso
LanguageReference
IsArrayFunctionIsDateFunctionIsEmptyFunctionIsNullFunctionIsNumericFunctionIsObjectFunctionVarTypeFunction
Microsoft®VisualBasic®ScriptingEditionUBoundFunctionSeeAlso
LanguageReference
DimStatementLBoundFunctionReDimStatement
Microsoft®VisualBasic®ScriptingEditionUCaseFunctionSeeAlso
LanguageReference
LCaseFunction
Microsoft®VisualBasic®ScriptingEditionValuePropertySeeAlso
LanguageReference
FirstIndexPropertyLengthProperty
Microsoft®VisualBasic®ScriptingEditionValuePropertyAppliesTo
LanguageReference
MatchObject
Microsoft®VisualBasic®ScriptingEdition
VarTypeConstantsSeeAlso
LanguageReference
ColorConstantsComparisonConstantsDateandTimeConstantsDateFormatConstantsMiscellaneousConstantsMsgBoxConstantsStringConstantsTristateConstants
Microsoft®VisualBasic®ScriptingEdition
VarTypeFunctionSeeAlso
LanguageReference
IsArrayFunctionIsDateFunctionIsEmptyFunctionIsNullFunctionIsNumericFunctionIsObjectFunctionTypeNameFunction
Microsoft®VisualBasic®ScriptingEdition
VBScriptConstantsSeeAlso
LanguageReference
FileSystemObjectConstants
Microsoft®VisualBasic®ScriptingEdition
WeekdayFunctionSeeAlso
LanguageReference
DateFunctionDayFunctionMonthFunctionNowFunctionYearFunction
Microsoft®VisualBasic®ScriptingEdition
While...WendStatementSeeAlso
LanguageReference
Do...LoopStatement
Microsoft®VisualBasic®ScriptingEditionWithStatementSeeAlso
LanguageReference
SetStatement
Microsoft®VisualBasic®ScriptingEditionXorOperatorSeeAlso
LanguageReference
AndOperatorLogicalOperatorsNotOperatorOperatorPrecedenceOperatorSummaryOrOperator
Microsoft®VisualBasic®ScriptingEditionYearFunctionSeeAlso
LanguageReference
DateFunctionDayFunctionMonthFunctionNowFunctionWeekdayFunction
Microsoft®VisualBasic®ScriptingEditionColorConstantsSeeAlso
LanguageReference
ComparisonConstantsDateandTimeConstantsDateFormatConstantsMiscellaneousConstantsMsgBoxConstantsStringConstantsTristateConstantsVarTypeConstants
Microsoft®VisualBasic®ScriptingEditionTristateConstantsSeeAlso
LanguageReference
ColorConstantsComparisonConstantsDateandTimeConstantsDateFormatConstantsMiscellaneousConstantsMsgBoxConstantsStringConstantsVarTypeConstants
Microsoft®VisualBasic®ScriptingEdition
ComparisonOperatorsSeeAlso
LanguageReference
=OperatorIsOperatorOperatorPrecedenceOperatorSummary
Microsoft®VisualBasic®ScriptingEdition
ExecuteGlobalStatement
LanguageReferenceVersion5
SeeAlso
Description
Executesoneormorespecifiedstatementsintheglobalnamespaceofascript.
Syntax
ExecuteGlobalstatement
Therequiredstatementargumentisastringexpressioncontainingoneormorestatementsforexecution.Includemultiplestatementsinthestatementargument,usingcolonsorembeddedlinebreakstoseparatethem.
Remarks
InVBScript,x=ycanbeinterpretedtwoways.Thefirstisasanassignmentstatement,wherethevalueofyisassignedtox.Thesecondinterpretationisasanexpressionthattestsifxandyhavethesamevalue.Iftheydo,resultisTrue;iftheyarenot,resultisFalse.TheExecuteGlobalstatementalwaysusesthefirstinterpretation,whereastheEvalmethodalwaysusesthesecond.
NoteInMicrosoft®JScript�,noconfusionexistsbetweenassignmentandcomparison,becausetheassignmentoperator(=)isdifferentfromthecomparisonoperator(==).
AllstatementsusedwithExecuteGlobalareexecutedinthescript'sglobalnamespace.Thisallowscodetobeaddedtotheprogramsothatanyprocedurecanaccessit.Forexample,aVBScriptClassstatementcanbeexecutedatruntimeandfunctionscansubsequentlycreatenewinstancesoftheclass.
Addingproceduresandclassesatruntimecanbeuseful,butalsointroducesthepossibilityofoverwritingexistingglobalvariablesandfunctionsatruntime.Becausethiscancausesignificantprogrammingproblems,careshouldbeexercisedwhenusingtheExecuteGlobalstatement.Ifyoudon�tneedaccesstoavariableorfunctionoutsideofaprocedure,usetheExecutestatementwhich
willonlyaffectthenamespaceofthecallingfunction.
ThefollowingexampleillustratestheuseoftheExecuteGlobalstatement:
DimX 'DeclareXinglobalscope.X="Global" 'AssignglobalXavalue.SubProc1 'Declareprocedure.DimX 'DeclareXinlocalscope.X="Local" 'AssignlocalXavalue. 'TheExecutestatementherecreatesa 'procedurethat,wheninvoked,printsX. 'ItprinttheglobalXbecauseProc2 'inheritseverythinginglobalscope.ExecuteGlobal"SubProc2:PrintX:EndSub"PrintEval("X") 'PrintlocalX.Proc2 'InvokeProc2inGlobalscoperesulting 'in"Global"beingprinted.EndSubProc2 'Thislinecausesanerrorsince 'Proc2isunavailableoutsideProc1.Proc1 'InvokeProc1.Execute"SubProc2:PrintX:EndSub"Proc2 'ThisinvocationsucceedsbecauseProc2 'isnowavailableglobally.
ThefollowingexampleshowshowtheExecuteGlobalstatementcanberewrittensoyoudon'thavetoenclosetheentireprocedureinthequotationmarks:
S="SubProc2"&vbCrLfS=S&"PrintX"&vbCrLfS=S&"EndSub"ExecuteGlobalS
Microsoft®VisualBasic®ScriptingEdition
GetLocaleFunction
LanguageReferenceVersion5
SeeAlso
Description
ReturnsthecurrentlocaleIDvalue.
Syntax
GetLocale()
Remarks
Alocaleisasetofuserpreferenceinformationrelatedtotheuser'slanguage,country/region,andculturalconventions.Thelocaledeterminessuchthingsaskeyboardlayout,alphabeticsortorder,aswellasdate,time,number,andcurrencyformats.
Thereturnvaluecanbeanyofthe32-bitvaluesshownintheLocaleIDchart:
ThefollowingexampleillustratestheuseoftheGetLocalefunction.Tousethiscode,pastetheentireexamplebetweenthe<BODY>l;tagsofastandardHTMLpage.
EnterDateinUKformat:<inputtype="text"id="UKDate"size="20"><p>Here'stheUSequivalent:<inputtype="text"id="USdate"size="20"><p><inputtype="button"value="Convert"id="button1"><p>EnterapriceinGerman: <inputtype="text"id="GermanNumber"size="20"><p>Here'stheUKequivalent:<inputtype="text"id="USNumber"size="20"><p><inputtype="button"value="Convert"id="button2"><p>
<scriptlanguage="vbscript">
DimcurrentLocale'GetthecurrentlocalecurrentLocale=GetLocale
SubButton1_onclickDimoriginaloriginal=SetLocale("en-gb")mydate=CDate(UKDate.value)'IEalwayssetsthelocaletoUSEnglishsousethe'currentLocalevariabletosetthelocaletoUSEnglishoriginal=SetLocale(currentLocale)USDate.value=FormatDateTime(mydate,vbShortDate)EndSub
Subbutton2_onclickDimoriginaloriginal=SetLocale("de")myvalue=CCur(GermanNumber.value)original=SetLocale("en-gb")USNumber.value=FormatCurrency(myvalue)EndSub
</script>
Microsoft®VisualBasic®Scripting
EditionLocaleID(LCID)Chart
LanguageReferenceVersion5
SeeAlso
LocaleDescription ShortString HexValue Decimal
Value LocaleDescription ShortString HexValue Decimal
Value
Afrikaans af 0x0436 1078 Hebrew he 0x040D 1037
Albanian sq 0x041C 1052 Hindi hi 0x0439 1081
Arabic-U.A.E. ar-ae 0x3801 14337 Hungarian hu 0x040E 1038
Arabic-Bahrain ar-bh 0x3C01 15361 Icelandic is 0x040F 1039
Arabic-Algeria ar-dz
0x1401 5121 Indonesian in 0x0421 1057
Arabic-Egypt ar-eg 0x0C01 3073 Italian-Standard it 0x0410 1040
Arabic-Iraq ar-iq 0x0801 2049 Italian-Switzerland
it-ch 0x0810 2064
Arabic-Jordan ar-jo 0x2C01 11265 Japanese ja 0x0411 1041
Arabic-Kuwait ar-kw 0x3401 13313 Korean ko 0x0412 1042
Arabic-Lebanon ar-lb 0x3001 12289 Latvian lv 0x0426 1062
Arabic-Libya ar-ly 0x1001 4097 Lithuanian lt 0x0427 1063
Arabic-Morocco ar-ma 0x1801 6145 Macedonian mk 0x042F 1071
Arabic-Oman ar-om 0x2001 8193 Malay-Malaysia ms 0x043E 1086
Arabic-Qatar ar-qa 0x4001 16385 Maltese mt 0x043A 1082
Arabic-SaudiaArabia
ar-sa 0x0401 1025
Norwegian-Bokmål no 0x0414 1044
Arabic-Syria ar-sy 0x2801 10241 Polish pl 0x0415 1045
Arabic-Tunisia ar-tn 0x1C01 7169 Portuguese-Standard pt 0x0816 2070
Arabic-Yemen ar-ye 0x2401 9217 Portuguese-Brazil
pt-br 0x0416 1046
Basque eu 0x042D 1069 Raeto-Romance rm 0x0417 1047
Belarusian be 0x0423 1059 Romanian ro 0x0418 1048
Bulgarian bg 0x0402 1026 Romanian-Moldovaro-mo 0x0818 2072
Catalan ca 0x0403 1027 Russian ru 0x0419 1049
Chinese zh 0x0004 4 Russian-Moldovaru-mo 0x0819 2073
Chinese-PRC zh-cn 0x0804 2052 Serbian-Cyrillic sr 0x0C1A 3098
Chinese-HongKong
zh-hk
0x0C04 3076 Setsuana tn 0x0432 1074
Chinese-Singapore
zh-sg 0x1004 4100 Slovenian sl 0x0424 1060
Chinese-Taiwan zh-tw 0x0404 1028 Slovak sk 0x041B 1051
Croatian hr 0x041A 1050 Sorbian sb 0x042E 1070
Czech cs 0x0405 1029 Spanish-Standard es 0x040A 1034
Danish da 0x0406 1030 Spanish-Argentinaes-ar 0x2C0A 11274
Dutch nl 0x0413 1043 Spanish-Bolivia es-bo 0x400A 16394
Dutch-Belgium nl-be 0x0813 2067 Spanish-Chile es-
cl 0x340A 13322
English en 0x0009 9 Spanish-Columbiaes-co 0x240A 9226
English-Australia
en-au 0x0C09 3081 Spanish-CostaRica
es-cr 0x140A 5130
English-Belizeen-bz 0x2809 10249
Spanish-DominicanRepublic
es-do 0x1C0A 7178
English-Canada en-ca 0x1009 4105 Spanish-Ecuador
es-ec 0x300A 12298
English-Ireland en-ie 0x1809 6153 Spanish-Guatemala
es-gt 0x100A 4106
English-Jamaica en-jm 0x2009 8201 Spanish-Honduras
es-hn 0x480A 18442
English-NewZealand
en-nz 0x1409 5129 Spanish-Mexico es-
mx 0x080A 2058
English-SouthAfrica
en-za 0x1C09 7177 Spanish-Nicaragua
es-ni 0x4C0A 19466
English-Trinidad en-tt 0x2C09 11273 Spanish-Panama es-pa 0x180A 6154
English-UnitedKingdom
en-gb 0x0809 2057 Spanish-Peru es-
pe 0x280A 10250
English-UnitedStates
en-us 0x0409 1033 Spanish-PuertoRico
es-pr 0x500A 20490
Spanish- es-
Estonian et 0x0425 1061 Paraguay py 0x3C0A 15370
Farsi fa 0x0429 1065Spanish-ElSalvador
es-sv 0x440A 17418
Finnish fi 0x040B 1035 Spanish-Uruguayes-uy 0x380A 14346
Faeroese fo 0x0438 1080 Spanish-Venezuelaes-ve 0x200A 8202
French-Standard fr 0x040C 1036 Sutu sx 0x0430 1072
French-Belgium fr-be 0x080C 2060 Swedish sv 0x041D 1053
French-Canada fr-ca 0x0C0C 3084 Swedish-Finland sv-fi 0x081D 2077
French-Luxembourg
fr-lu 0x140C 5132 Thai th 0x041E 1054
French-Switzerland
fr-ch 0x100C 4108 Turkish tr 0x041F 1055
Gaelic-Scotland gd 0x043C 1084 Tsonga ts 0x0431 1073
German-
Standard de 0x0407 1031 Ukranian uk 0x0422 1058
German-Austrian
de-at 0x0C07 3079 Urdu-Pakistan ur 0x0420 1056
German-Lichtenstein
de-li 0x1407 5127 Vietnamese vi 0x042A 1066
German-Luxembourg
de-lu 0x1007 4103 Xhosa xh 0x0434 1076
German-Switzerland
de-ch 0x0807 2055 Yiddish ji 0x043D 1085
Greek el 0x0408 1032 Zulu zu 0x0435 1077
Microsoft®VisualBasic®ScriptingEdition
SetLocaleFunction
LanguageReferenceVersion5
SeeAlso
Description
Setsthegloballocaleandreturnsthepreviouslocale.
Syntax
SetLocale(lcid)
Thelcidargumentcanbeanyvalid32-bitvalueorshortstringthatuniquelyidentifiesageographicallocale.RecognizedvaluescanbefoundintheLocaleIDchart.
Remarks
Iflcidiszero,thelocaleissettomatchthecurrentsystemsetting.
Alocaleisasetofuserpreferenceinformationrelatedtotheuser'slanguage,country/region,andculturalconventions.Thelocaledeterminessuchthingsaskeyboardlayout,alphabeticsortorder,aswellasdate,time,number,andcurrencyformats.
ThefollowingexampleillustratestheuseoftheSetLocalefunction.Tousethiscode,pastetheentireexamplebetweenthe<BODY>tagsofastandardHTMLpage.
EnterDateinUKformat:<inputtype="text"id="UKDate"size="20"><p>Here'stheUSequivalent:<inputtype="text"id="USdate"size="20"><p><inputtype="button"value="Convert"id="button1"><p>EnterapriceinGerman: <inputtype="text"id="GermanNumber"size="20"><p>Here'stheUKequivalent:<inputtype="text"id="USNumber"size="20"><p><inputtype="button"value="Convert"id="button2"><p>
<scriptlanguage="vbscript">DimcurrentLocale'GetthecurrentlocalecurrentLocale=GetLocale
SubButton1_onclickDimoriginaloriginal=SetLocale("en-gb")mydate=CDate(UKDate.value)'IEalwayssetsthelocaletoUSEnglishsousethe'currentLocalevariabletosetthelocaletoUSEnglishoriginal=SetLocale(currentLocale)USDate.value=FormatDateTime(mydate,vbShortDate)EndSub
Subbutton2_onclickDimoriginal
original=SetLocale("de")myvalue=CCur(GermanNumber.value)original=SetLocale("en-gb")USNumber.value=FormatCurrency(myvalue)EndSub
</script>
Microsoft®VisualBasic®ScriptingEditionAddMethod(Dictionary)SeeAlso
ScriptingRun-TimeReference
AddMethod(Folders)ExistsMethodItemsMethodKeysMethodRemoveMethodRemoveAllMethod
Microsoft®VisualBasic®ScriptingEditionAddMethod(Dictionary)AppliesTo
ScriptingRun-TimeReference
DictionaryObject
Microsoft®VisualBasic®ScriptingEditionAddMethod(Folders)SeeAlso
ScriptingRun-TimeReference
AddMethod(Dictionary)
Microsoft®VisualBasic®ScriptingEditionAddMethod(Folders)AppliesTo
ScriptingRun-TimeReference
FoldersCollection
Microsoft®VisualBasic®ScriptingEdition
AtEndOfLinePropertySeeAlso
ScriptingRun-TimeReference
AtEndOfStreamPropertyColumnPropertyLineProperty
Microsoft®VisualBasic®ScriptingEdition
AtEndOfLinePropertyAppliesTo
ScriptingRun-TimeReference
TextStreamObject
Microsoft®VisualBasic®ScriptingEdition
AtEndOfStreamPropertySeeAlso
ScriptingRun-TimeReference
AtEndOfLinePropertyColumnPropertyLineProperty
Microsoft®VisualBasic®ScriptingEdition
AtEndOfStreamPropertyAppliesTo
ScriptingRun-TimeReferenceVersion
TextStreamObject
Microsoft®VisualBasic®ScriptingEdition
AttributesPropertySeeAlso
ScriptingRun-TimeReference
DateCreatedPropertyDateLastAccessedPropertyDateLastModifiedPropertyDrivePropertyFilesPropertyIsRootFolderPropertyNamePropertyParentFolderPropertyPathPropertyShortNamePropertyShortPathPropertySizePropertySubFoldersPropertyTypeProperty
Microsoft®VisualBasic®ScriptingEdition
AttributesPropertyAppliesTo
ScriptingRun-TimeReference
FileObjectFolderObject
Microsoft®VisualBasic®ScriptingEdition
AvailableSpacePropertySeeAlso
ScriptingRun-TimeReference
DriveLetterPropertyDriveTypePropertyFileSystemPropertyFreeSpacePropertyIsReadyPropertyPathPropertyRootFolderPropertySerialNumberPropertyShareNamePropertyTotalSizePropertyVolumeNameProperty
Microsoft®VisualBasic®ScriptingEdition
AvailableSpacePropertyAppliesTo
ScriptingRun-TimeReference
DriveObject
Microsoft®VisualBasic®ScriptingEdition
BuildPathMethodSeeAlso
ScriptingRun-TimeReference
GetAbsolutePathNameMethodGetBaseNameMethodGetDriveNameMethodGetExtensionNameMethodGetFileNameMethodGetParentFolderNameMethodGetTempNameMethod
Microsoft®VisualBasic®ScriptingEdition
BuildPathMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEditionCloseMethodSeeAlso
ScriptingRun-TimeReference
ReadMethodReadAllMethodReadLineMethodSkipMethodSkipLineMethodWriteMethodWriteLineMethodWriteBlankLinesMethod
Microsoft®VisualBasic®ScriptingEditionCloseMethodAppliesTo
ScriptingRun-TimeReference
TextStreamObject
Microsoft®VisualBasic®ScriptingEditionColumnPropertySeeAlso
ScriptingRun-TimeReference
AtEndOfLinePropertyAtEndOfStreamPropertyLineProperty
Microsoft®VisualBasic®ScriptingEditionColumnPropertyAppliesTo
ScriptingRun-TimeReference
TextStreamObject
Microsoft®VisualBasic®ScriptingEdition
CompareModePropertySeeAlso
ScriptingRun-TimeReference
CountPropertyItemPropertyKeyProperty
Microsoft®VisualBasic®ScriptingEdition
CompareModePropertyAppliesTo
ScriptingRun-TimeReference
DictionaryObject
Microsoft®VisualBasic®ScriptingEditionCopyMethodSeeAlso
ScriptingRun-TimeReference
CopyFileMethodCopyFolderMethodDeleteMethodMoveMethodOpenAsTextStreamMethod
Microsoft®VisualBasic®ScriptingEditionCopyMethodAppliesTo
ScriptingRun-TimeReference
FileObjectFolderObject
Microsoft®VisualBasic®ScriptingEdition
CopyFileMethodSeeAlso
ScriptingRun-TimeReference
CopyMethodCopyFolderMethodCreateTextFileMethodDeleteFileMethodMoveFileMethod
Microsoft®VisualBasic®ScriptingEdition
CopyFileMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEdition
CopyFolderMethodSeeAlso
ScriptingRun-TimeReference
CopyFileMethodCopyMethodCreateFolderMethodDeleteFolderMethodMoveFolderMethod
Microsoft®VisualBasic®ScriptingEdition
CopyFolderMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEditionCountPropertySeeAlso
ScriptingRun-TimeReference
CompareModePropertyItemPropertyKeyProperty
Microsoft®VisualBasic®ScriptingEditionCountPropertyAppliesTo
ScriptingRun-TimeReference
DictionaryObjectDrivesCollectionFilesCollectionFoldersCollectionMatchesCollection
Microsoft®VisualBasic®ScriptingEdition
CreateFolderMethodSeeAlso
ScriptingRun-TimeReference
CopyFolderMethodDeleteFolderMethodMoveFolderMethod
Microsoft®VisualBasic®ScriptingEdition
CreateFolderMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEdition
CreateTextFileMethodSeeAlso
ScriptingRun-TimeReference
CreateFolderMethodOpenAsTextStreamMethodOpenTextFileMethod
Microsoft®VisualBasic®ScriptingEdition
CreateTextFileMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObjectFolderObject
Microsoft®VisualBasic®ScriptingEdition
DateCreatedPropertySeeAlso
ScriptingRun-TimeReference
AttributesPropertyDateLastAccessedPropertyDateLastModifiedPropertyDrivePropertyFilesPropertyIsRootFolderPropertyNamePropertyParentFolderPropertyPathPropertyShortNamePropertyShortPathPropertySizePropertySubFoldersPropertyTypeProperty
Microsoft®VisualBasic®ScriptingEdition
DateCreatedPropertyAppliesTo
ScriptingRun-TimeReference
FileObjectFolderObject
Microsoft®VisualBasic®ScriptingEdition
DateLastAccessedPropertySeeAlso
ScriptingRun-TimeReference
AttributesPropertyDateCreatedPropertyDateLastModifiedPropertyDrivePropertyFilesPropertyIsRootFolderPropertyNamePropertyParentFolderPropertyPathPropertyShortNamePropertyShortPathPropertySizePropertySubFoldersPropertyTypeProperty
Microsoft®VisualBasic®ScriptingEdition
DateLastAccessedPropertyAppliesTo
ScriptingRun-TimeReference
FileObjectFolderObject
Microsoft®VisualBasic®ScriptingEdition
DateLastModifiedPropertySeeAlso
ScriptingRun-TimeReference
AttributesPropertyDateCreatedPropertyDateLastAccessedPropertyDrivePropertyFilesPropertyIsRootFolderPropertyNamePropertyParentFolderPropertyPathPropertyShortNamePropertyShortPathPropertySizePropertySubFoldersPropertyTypeProperty
Microsoft®VisualBasic®ScriptingEdition
DateLastModifiedPropertyAppliesTo
ScriptingRun-TimeReference
FileObjectFolderObject
Microsoft®VisualBasic®ScriptingEditionDeleteMethodSeeAlso
ScriptingRun-TimeReference
CopyMethodDeleteFileMethodDeleteFolderMethodMoveMethodOpenAsTextStreamMethod
Microsoft®VisualBasic®ScriptingEditionDeleteMethodAppliesTo
ScriptingRun-TimeReference
FileObjectFolderObject
Microsoft®VisualBasic®ScriptingEdition
DeleteFileMethodSeeAlso
ScriptingRun-TimeReference
CopyFileMethodCreateTextFileMethodDeleteMethodDeleteFolderMethodMoveFileMethod
Microsoft®VisualBasic®ScriptingEdition
DeleteFileMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEdition
DeleteFolderMethodSeeAlso
ScriptingRun-TimeReference
CopyFolderMethodCreateFolderMethodDeleteMethodDeleteFileMethodMoveFolderMethod
Microsoft®VisualBasic®ScriptingEdition
DeleteFolderMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEdition
DictionaryObjectSeeAlso
ScriptingRun-TimeReference
FileSystemObjectObjectTextStreamObject
Microsoft®VisualBasic®ScriptingEdition
DictionaryObjectProperties
ScriptingRun-TimeReference
CompareModePropertyCountPropertyItemPropertyKeyProperty
Microsoft®VisualBasic®ScriptingEdition
DictionaryObjectMethods
ScriptingRun-TimeReference
AddMethod(Dictionary)ExistsMethodItemsMethodKeysMethodRemoveMethodRemoveAllMethod
Microsoft®VisualBasic®ScriptingEditionDriveObjectSeeAlso
ScriptingRun-TimeReference
DrivesCollectionFileObjectFilesCollectionFolderObjectFoldersCollectionGetDriveMethod
Microsoft®VisualBasic®ScriptingEditionDriveObjectProperties
ScriptingRun-TimeReference
AvailableSpacePropertyDriveLetterPropertyDriveTypePropertyFileSystemPropertyFreeSpacePropertyIsReadyPropertyPathPropertyRootFolderPropertySerialNumberPropertyShareNamePropertyTotalSizePropertyVolumeNameProperty
Microsoft®VisualBasic®ScriptingEditionDriveObjectMethods
ScriptingRun-TimeReference
TheDriveobjecthasnomethods.
Microsoft®VisualBasic®ScriptingEditionDrivePropertySeeAlso
ScriptingRun-TimeReference
AttributesPropertyDateCreatedPropertyDateLastAccessedPropertyDateLastModifiedPropertyFilesPropertyIsRootFolderPropertyNamePropertyParentFolderPropertyPathPropertyShortNamePropertyShortPathPropertySizePropertySubFoldersPropertyTypeProperty
Microsoft®VisualBasic®ScriptingEditionDrivePropertyAppliesTo
ScriptingRun-TimeReference
FileObjectFolderObject
Microsoft®VisualBasic®ScriptingEdition
DriveExistsMethodSeeAlso
ScriptingRun-TimeReference
DriveObjectDrivesCollectionFileExistsMethodFolderExistsMethodGetDriveMethodGetDriveNameMethodIsReadyProperty
Microsoft®VisualBasic®ScriptingEdition
DriveExistsMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEdition
DriveLetterPropertySeeAlso
ScriptingRun-TimeReference
AvailableSpacePropertyDriveTypePropertyFileSystemPropertyFreeSpacePropertyIsReadyPropertyPathPropertyRootFolderPropertySerialNumberPropertyShareNamePropertyTotalSizePropertyVolumeNameProperty
Microsoft®VisualBasic®ScriptingEdition
DriveLetterPropertyAppliesTo
ScriptingRun-TimeReference
DriveObject
Microsoft®VisualBasic®ScriptingEditionDrivesCollectionSeeAlso
ScriptingRun-TimeReference
DriveObjectDrivesPropertyFileObjectFilesCollectionFolderObjectFoldersCollection
Microsoft®VisualBasic®ScriptingEditionDrivesCollectionProperties
ScriptingRun-TimeReference
CountPropertyItemProperty
Microsoft®VisualBasic®ScriptingEditionDrivesCollectionMethods
ScriptingRun-TimeReference
TheDrivescollectionhasnomethods.
Microsoft®VisualBasic®ScriptingEditionDrivesPropertySeeAlso
ScriptingRun-TimeReference
DrivesCollectionFilesPropertySubFoldersProperty
Microsoft®VisualBasic®ScriptingEditionDrivesPropertyAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEdition
DriveTypeConstantsSeeAlso
ScriptingRun-TimeReference
ComparisonConstantsFileAttributeConstantsFileInput/OutputConstantsSpecialFolderConstantsTristateConstants
Microsoft®VisualBasic®ScriptingEdition
DriveTypePropertySeeAlso
ScriptingRun-TimeReference
AvailableSpacePropertyDriveLetterPropertyFileSystemPropertyFreeSpacePropertyIsReadyPropertyPathPropertyRootFolderPropertySerialNumberPropertyShareNamePropertyTotalSizePropertyVolumeNameProperty
Microsoft®VisualBasic®ScriptingEdition
DriveTypePropertyAppliesTo
ScriptingRun-TimeReference
DriveObject
Microsoft®VisualBasic®ScriptingEditionExistsMethodSeeAlso
LanguageReference
AddMethod(Dictionary)ItemsMethodKeysMethodRemoveMethodRemoveAllMethod
Microsoft®VisualBasic®ScriptingEditionExistsMethodAppliesTo
LanguageReference
DictionaryObject
Microsoft®VisualBasic®ScriptingEdition
FileAttributeConstantsSeeAlso
ScriptingRun-TimeReference
ComparisonConstantsDriveTypeConstantsFileInput/OutputConstantsSpecialFolderConstantsTristateConstants
Microsoft®VisualBasic®ScriptingEditionFileInput/OutputConstantsSeeAlso
ScriptingRun-TimeReference
ComparisonConstantsDriveTypeConstantsFileAttributeConstantsSpecialFolderConstantsTristateConstants
Microsoft®VisualBasic®ScriptingEdition
FileExistsMethodSeeAlso
ScriptingRun-TimeReference
DriveExistsMethodFolderExistsMethodGetFileMethodGetFileNameMethod
Microsoft®VisualBasic®ScriptingEdition
FileExistsMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEditionFileObjectSeeAlso
ScriptingRun-TimeReference
DriveObjectDrivesCollectionFilesCollectionFolderObjectFoldersCollection
Microsoft®VisualBasic®ScriptingEditionFileObjectProperties
ScriptingRun-TimeReference
AttributesPropertyDateCreatedPropertyDateLastAccessedPropertyDateLastModifiedPropertyDrivePropertyNamePropertyParentFolderPropertyPathPropertyShortNamePropertyShortPathPropertySizePropertyTypeProperty
Microsoft®VisualBasic®ScriptingEditionFileObjectMethods
ScriptingRun-TimeReference
CopyMethodDeleteMethodMoveMethodOpenAsTextStreamMethod
Microsoft®VisualBasic®ScriptingEditionFilesCollectionSeeAlso
ScriptingRun-TimeReference
DriveObjectDrivesCollectionFileObjectFolderObjectFoldersCollection
Microsoft®VisualBasic®ScriptingEditionFilesCollectionProperties
ScriptingRun-TimeReference
CountPropertyItemProperty
Microsoft®VisualBasic®ScriptingEditionFilesCollectionMethods
ScriptingRun-TimeReference
TheFilescollectionhasnomethods.
Microsoft®VisualBasic®ScriptingEditionFilesPropertySeeAlso
ScriptingRun-TimeReference
AttributesPropertyDateCreatedPropertyDateLastAccessedPropertyDateLastModifiedPropertyDrivesPropertyIsRootFolderPropertyNamePropertyParentFolderPropertyPathPropertyShortNamePropertyShortPathPropertySizePropertySubFoldersPropertyTypeProperty
Microsoft®VisualBasic®ScriptingEditionFilesPropertyAppliesTo
ScriptingRun-TimeReference
FolderObject
Microsoft®VisualBasic®ScriptingEdition
FileSystemObjectObjectSeeAlso
ScriptingRun-TimeReference
CreateObjectFunctionDictionaryObjectDriveObjectDrivesCollectionFileObjectFileSystemPropertyFilesCollectionFolderObjectFoldersCollectionTextStreamObject
Microsoft®VisualBasic®ScriptingEdition
FileSystemObjectObjectProperties
ScriptingRun-TimeReference
DrivesProperty
Microsoft®VisualBasic®ScriptingEdition
FileSystemObjectObjectMethods
ScriptingRun-TimeReference
BuildPathMethodCopyFileMethodCopyFolderMethodCreateFolderMethodCreateTextFileMethodDeleteFileMethodDeleteFolderMethodDriveExistsMethodFileExistsMethodFolderExistsMethodGetAbsolutePathNameMethodGetBaseNameMethodGetDriveMethodGetDriveNameMethodGetExtensionNameMethodGetFileMethodGetFileNameMethodGetFolderMethodGetParentFolderNameMethodGetSpecialFolderMethodGetTempNameMethodMoveFileMethodMoveFolderMethodOpenTextFileMethod
Microsoft®VisualBasic®ScriptingEdition
FileSystemObjectConstantsSeeAlso
ScriptingRun-TimeReference
VBScriptConstants
Microsoft®VisualBasic®ScriptingEdition
FileSystemPropertySeeAlso
ScriptingRun-TimeReference
AvailableSpacePropertyDriveLetterPropertyDriveTypePropertyFileSystemObjectObjectFreeSpacePropertyIsReadyPropertyPathPropertyRootFolderPropertySerialNumberPropertyShareNamePropertyTotalSizePropertyVolumeNameProperty
Microsoft®VisualBasic®ScriptingEdition
FileSystemPropertyAppliesTo
ScriptingRun-TimeReference
DriveObject
Microsoft®VisualBasic®ScriptingEditionFolderObjectSeeAlso
ScriptingRun-TimeReference
DriveObjectDrivesCollectionFileObjectFilesCollectionFoldersCollection
Microsoft®VisualBasic®ScriptingEditionFolderObjectProperties
ScriptingRun-TimeReference
AttributesPropertyDateCreatedPropertyDateLastAccessedPropertyDateLastModifiedPropertyDrivePropertyFilesPropertyIsRootFolderPropertyNamePropertyParentFolderPropertyPathPropertyShortNamePropertyShortPathPropertySizePropertySubFoldersPropertyTypeProperty
Microsoft®VisualBasic®ScriptingEditionFolderObjectMethods
ScriptingRun-TimeReference
CopyMethodDeleteMethodMoveMethodCreateTextFileMethod
Microsoft®VisualBasic®ScriptingEditionFoldersCollectionSeeAlso
ScriptingRun-TimeReference
DriveObjectDrivesCollectionFileObjectFilesCollectionFolderObjectSubFoldersProperty
Microsoft®VisualBasic®ScriptingEditionFoldersCollectionProperties
ScriptingRun-TimeReference
CountPropertyItemProperty
Microsoft®VisualBasic®ScriptingEditionFoldersCollectionMethods
ScriptingRun-TimeReference
AddMethod
Microsoft®VisualBasic®ScriptingEdition
FolderExistsMethodSeeAlso
ScriptingRun-TimeReference
DriveExistsMethodFileExistsMethodGetFolderMethodGetParentFolderNameMethod
Microsoft®VisualBasic®ScriptingEdition
FolderExistsMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEdition
FreeSpacePropertySeeAlso
ScriptingRun-TimeReference
AvailableSpacePropertyDriveLetterPropertyDriveTypePropertyFileSystemPropertyIsReadyPropertyPathPropertyRootFolderPropertySerialNumberPropertyShareNamePropertyTotalSizePropertyVolumeNameProperty
Microsoft®VisualBasic®ScriptingEdition
FreeSpacePropertyAppliesTo
ScriptingRun-TimeReference
DriveObject
Microsoft®VisualBasic®ScriptingEdition
GetAbsolutePathNameMethodSeeAlso
ScriptingRun-TimeReference
GetBaseNameMethodGetDriveMethodGetDriveNameMethodGetExtensionNameMethodGetFileMethodGetFileNameMethodGetFileVersionMethodGetFolderMethodGetParentFolderNameMethodGetSpecialFolderMethodGetTempNameMethod
Microsoft®VisualBasic®ScriptingEdition
GetAbsolutePathNameMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEdition
GetBaseNameMethodSeeAlso
ScriptingRun-TimeReference
GetAbsolutePathNameMethodGetDriveMethodGetDriveNameMethodGetExtensionNameMethodGetFileMethodGetFileNameMethodGetFileVersionMethodGetFolderMethodGetParentFolderNameMethodGetSpecialFolderMethodGetTempNameMethod
Microsoft®VisualBasic®ScriptingEdition
GetBaseNameMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEdition
GetDriveMethodSeeAlso
ScriptingRun-TimeReference
GetAbsolutePathNameMethodGetBaseNameMethodGetDriveNameMethodGetExtensionNameMethodGetFileMethodGetFileNameMethodGetFileVersionMethodGetFolderMethodGetParentFolderNameMethodGetSpecialFolderMethodGetTempNameMethod
Microsoft®VisualBasic®ScriptingEdition
GetDriveMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEdition
GetDriveNameMethodSeeAlso
ScriptingRun-TimeReference
GetAbsolutePathNameMethodGetBaseNameMethodGetDriveMethodGetExtensionNameMethodGetFileMethodGetFileNameMethodGetFileVersionMethodGetFolderMethodGetParentFolderNameMethodGetSpecialFolderMethodGetTempNameMethod
Microsoft®VisualBasic®ScriptingEdition
GetDriveNameMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEdition
GetExtensionNameMethodSeeAlso
ScriptingRun-TimeReference
GetAbsolutePathNameMethodGetBaseNameMethodGetDriveMethodGetDriveNameMethodGetFileMethodGetFileNameMethodGetFileVersionMethodGetFolderMethodGetParentFolderNameMethodGetSpecialFolderMethodGetTempNameMethod
Microsoft®VisualBasic®ScriptingEdition
GetExtensionNameMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEditionGetFileMethodSeeAlso
ScriptingRun-TimeReference
GetAbsolutePathNameMethodGetBaseNameMethodGetDriveMethodGetDriveNameMethodGetExtensionNameMethodGetFileNameMethodGetFileVersionMethodGetFolderMethodGetParentFolderNameMethodGetSpecialFolderMethodGetTempNameMethod
Microsoft®VisualBasic®ScriptingEditionGetFileMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEdition
GetFileNameMethodSeeAlso
ScriptingRun-TimeReference
GetAbsolutePathNameMethodGetBaseNameMethodGetDriveMethodGetDriveNameMethodGetExtensionNameMethodGetFileMethodGetFileVersionMethodGetFolderMethodGetParentFolderNameMethodGetSpecialFolderMethodGetTempNameMethod
Microsoft®VisualBasic®ScriptingEdition
GetFileNameMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEdition
GetFileVersionMethodSeeAlso
ScriptingRun-TimeReference
GetAbsolutePathNameMethodGetBaseNameMethodGetDriveMethodGetDriveNameMethodGetExtensionNameMethodGetFileMethodGetFileNameMethodGetFolderMethodGetParentFolderNameMethodGetSpecialFolderMethodGetTempNameMethod
Microsoft®VisualBasic®ScriptingEdition
GetFileVersionMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEdition
GetFolderMethodSeeAlso
ScriptingRun-TimeReference
GetAbsolutePathNameMethodGetBaseNameMethodGetDriveMethodGetDriveNameMethodGetExtensionNameMethodGetFileMethodGetFileNameMethodGetFileVersionMethodGetParentFolderNameMethodGetSpecialFolderMethodGetTempNameMethod
Microsoft®VisualBasic®ScriptingEdition
GetFolderMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEdition
GetParentFolderNameMethodSeeAlso
ScriptingRun-TimeReference
GetAbsolutePathNameMethodGetBaseNameMethodGetDriveMethodGetDriveNameMethodGetExtensionNameMethodGetFileMethodGetFileNameMethodGetFileVersionMethodGetFolderMethodGetSpecialFolderMethodGetTempNameMethod
Microsoft®VisualBasic®ScriptingEdition
GetParentFolderNameMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEdition
GetSpecialFolderMethodSeeAlso
ScriptingRun-TimeReference
GetAbsolutePathNameMethodGetBaseNameMethodGetDriveMethodGetDriveNameMethodGetExtensionNameMethodGetFileMethodGetFileNameMethodGetFileVersionMethodGetFolderMethodGetParentFolderNameMethodGetTempNameMethod
Microsoft®VisualBasic®ScriptingEdition
GetSpecialFolderMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEdition
GetTempNameMethodSeeAlso
ScriptingRun-TimeReference
GetAbsolutePathNameMethodGetBaseNameMethodGetDriveMethodGetDriveNameMethodGetExtensionNameMethodGetFileMethodGetFileNameMethodGetFileVersionMethodGetFolderMethodGetParentFolderNameMethodGetSpecialFolderMethod
Microsoft®VisualBasic®ScriptingEdition
GetTempNameMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEditionIsReadyPropertySeeAlso
ScriptingRun-TimeReference
AvailableSpacePropertyDriveLetterPropertyDriveTypePropertyFileSystemPropertyFreeSpacePropertyPathPropertyRootFolderPropertySerialNumberPropertyShareNamePropertyTotalSizePropertyVolumeNameProperty
Microsoft®VisualBasic®ScriptingEditionIsReadyPropertyAppliesTo
ScriptingRun-TimeReference
DriveObject
Microsoft®VisualBasic®ScriptingEdition
IsRootFolderPropertySeeAlso
ScriptingRun-TimeReference
AttributesPropertyDateCreatedPropertyDateLastAccessedPropertyDateLastModifiedPropertyDrivePropertyFilesPropertyNamePropertyParentFolderPropertyPathPropertyShortNamePropertyShortPathPropertySizePropertySubFoldersPropertyTypeProperty
Microsoft®VisualBasic®ScriptingEdition
IsRootFolderPropertyAppliesTo
ScriptingRun-TimeReference
FolderObject
Microsoft®VisualBasic®ScriptingEditionItemPropertySeeAlso
ScriptingRun-TimeReference
CompareModePropertyCountPropertyKeyProperty
Microsoft®VisualBasic®ScriptingEditionItemPropertyAppliesTo
ScriptingRun-TimeReference
DictionaryObjectDrivesCollectionFilesCollectionFoldersCollectionMatchesCollection
Microsoft®VisualBasic®ScriptingEditionItemsMethodSeeAlso
ScriptingRun-TimeReference
AddMethod(Dictionary)ExistsMethodKeysMethodRemoveMethodRemoveAllMethod
Microsoft®VisualBasic®ScriptingEditionItemsMethodAppliesTo
ScriptingRun-TimeReference
DictionaryObject
Microsoft®VisualBasic®ScriptingEditionKeyPropertySeeAlso
ScriptingRun-TimeReference
CompareModePropertyCountPropertyItemProperty
Microsoft®VisualBasic®ScriptingEditionKeyPropertyAppliesTo
ScriptingRun-TimeReference
DictionaryObject
Microsoft®ScriptingLibrary-FileSystemObject
FileSystemObjectGlossary
ScriptingRun-TimeReference
array
Asetofsequentiallyindexedelementshavingthesametypeofdata.Eachelementofanarrayhasauniqueidentifyingindexnumber.Changesmadetooneelementofanarraydonotaffecttheotherelements.
collectionAnobjectthatcontainsasetofrelatedobjects.Anobject'spositioninthecollectioncanchangewheneverachangeoccursinthecollection;therefore,thepositionofanyspecificobjectinthecollectionmayvary.
run-timeerrorAnerrorthatoccurswhencodeisrunning.Arun-timeerrorresultswhenastatementattemptsaninvalidoperation.
stringexpressionAnyexpressionthatevaluatestoasequenceofcontiguouscharacters.Elementsofastringexpressioncanincludeafunctionthatreturnsastring,astringliteral,astringconstant,orastringvariable.
typelibraryAfileorcomponentwithinanotherfilethatcontainsstandarddescriptionsofexposedobjects,properties,andmethods.
Microsoft®VisualBasic®ScriptingEditionKeysMethodSeeAlso
ScriptingRun-TimeReference
AddMethod(Dictionary)ExistsMethodItemsMethodRemoveMethodRemoveAllMethod
Microsoft®VisualBasic®ScriptingEditionKeysMethodAppliesTo
ScriptingRun-TimeReference
DictionaryObject
Microsoft®VisualBasic®ScriptingEditionLinePropertySeeAlso
ScriptingRun-TimeReference
AtEndOfStreamPropertyAtEndOfLinePropertyColumnProperty
Microsoft®VisualBasic®ScriptingEditionLinePropertyAppliesTo
ScriptingRun-TimeReferenceVersion
TextStreamObject
Microsoft®VisualBasic®ScriptingEditionMoveMethodSeeAlso
ScriptingRun-TimeReference
CopyMethodDeleteMethodMoveFileMethodMoveFolderMethodOpenAsTextStreamMethod
Microsoft®VisualBasic®ScriptingEditionMoveMethodAppliesTo
ScriptingRun-TimeReference
FileObjectFolderObject
Microsoft®VisualBasic®ScriptingEdition
MoveFileMethodSeeAlso
ScriptingRun-TimeReference
CopyFileMethodDeleteFileMethodGetFileMethodGetFileNameMethodMoveMethodMoveFolderMethodOpenTextFileMethod
Microsoft®VisualBasic®ScriptingEdition
MoveFileMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEdition
MoveFolderMethodSeeAlso
ScriptingRun-TimeReference
CopyFolderMethodCreateFolderMethodDeleteFolderMethodGetFolderMethodGetParentFolderNameMethodMoveMethodMoveFileMethod
Microsoft®VisualBasic®ScriptingEdition
MoveFolderMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEditionNamePropertySeeAlso
ScriptingRun-TimeReference
AttributesPropertyDateCreatedPropertyDateLastAccessedPropertyDateLastModifiedPropertyDrivePropertyFilesPropertyIsRootFolderPropertyParentFolderPropertyPathPropertyShortNamePropertyShortPathPropertySizePropertySubFoldersPropertyTypeProperty
Microsoft®VisualBasic®ScriptingEditionNamePropertyAppliesTo
ScriptingRun-TimeReference
FileObjectFolderObject
Microsoft®VisualBasic®ScriptingEdition
OpenAsTextStreamMethodSeeAlso
ScriptingRun-TimeReference
CopyMethodCreateTextFileMethodDeleteMethodMoveMethodOpenTextFileMethod
Microsoft®VisualBasic®ScriptingEdition
OpenAsTextStreamMethodAppliesTo
ScriptingRun-TimeReference
FileObject
Microsoft®VisualBasic®ScriptingEdition
OpenTextFileMethodSeeAlso
ScriptingRun-TimeReference
OpenAsTextStreamMethodCreateTextFileMethod
Microsoft®VisualBasic®ScriptingEdition
OpenTextFileMethodAppliesTo
ScriptingRun-TimeReference
FileSystemObjectObject
Microsoft®VisualBasic®ScriptingEdition
ParentFolderPropertySeeAlso
ScriptingRun-TimeReference
AttributesPropertyDateCreatedPropertyDateLastAccessedPropertyDateLastModifiedPropertyDrivePropertyFilesPropertyIsRootFolderPropertyNamePropertyPathPropertyShortNamePropertyShortPathPropertySizePropertySubFoldersPropertyTypeProperty
Microsoft®VisualBasic®ScriptingEdition
ParentFolderPropertyAppliesTo
ScriptingRun-TimeReference
FileObjectFolderObject
Microsoft®VisualBasic®ScriptingEditionPathPropertySeeAlso
ScriptingRun-TimeReference
AttributesPropertyAvailableSpacePropertyDateCreatedPropertyDateLastAccessedPropertyDateLastModifiedPropertyDrivePropertyDriveLetterPropertyDriveTypePropertyFilesPropertyFileSystemPropertyFreeSpacePropertyIsReadyPropertyIsRootFolderPropertyNamePropertyParentFolderPropertyRootFolderPropertySerialNumberPropertyShareNamePropertyShortNamePropertyShortPathPropertySizePropertySubFoldersPropertyTotalSizePropertyTypePropertyVolumeNameProperty
Microsoft®VisualBasic®ScriptingEditionPathPropertyAppliesTo
ScriptingRun-TimeReference
DriveObjectFileObjectFolderObject
Microsoft®VisualBasic®ScriptingEditionReadMethodSeeAlso
ScriptingRun-TimeReference
CloseMethodReadAllMethodReadLineMethodSkipMethodSkipLineMethodWriteMethodWriteLineMethodWriteBlankLinesMethod
Microsoft®VisualBasic®ScriptingEditionReadMethodAppliesTo
ScriptingRun-TimeReference
TextStreamObject
Microsoft®VisualBasic®ScriptingEditionReadAllMethodSeeAlso
ScriptingRun-TimeReference
CloseMethodReadMethodReadLineMethodSkipMethodSkipLineMethodWriteMethodWriteLineMethodWriteBlankLinesMethod
Microsoft®VisualBasic®ScriptingEditionReadAllMethodAppliesTo
ScriptingRun-TimeReference
TextStreamObject
Microsoft®VisualBasic®ScriptingEdition
ReadLineMethodSeeAlso
ScriptingRun-TimeReference
CloseMethodReadMethodReadAllMethodSkipMethodSkipLineMethodWriteMethodWriteLineMethodWriteBlankLinesMethod
Microsoft®VisualBasic®ScriptingEdition
ReadLineMethodAppliesTo
ScriptingRun-TimeReference
TextStreamObject
Microsoft®VisualBasic®ScriptingEditionRemoveMethodSeeAlso
ScriptingRun-TimeReference
AddMethod(Dictionary)ExistsMethodItemsMethodKeysMethodRemoveAllMethod
Microsoft®VisualBasic®ScriptingEditionRemoveMethodAppliesTo
ScriptingRun-TimeReference
DictionaryObject
Microsoft®VisualBasic®ScriptingEdition
RemoveAllMethodSeeAlso
ScriptingRun-TimeReference
AddMethod(Dictionary)ExistsMethodItemsMethodKeysMethodRemoveMethod
Microsoft®VisualBasic®ScriptingEdition
RemoveAllMethodAppliesTo
ScriptingRun-TimeReference
DictionaryObject
Microsoft®VisualBasic®ScriptingEdition
RootFolderPropertySeeAlso
ScriptingRun-TimeReference
AvailableSpacePropertyDriveLetterPropertyDriveTypePropertyFileSystemPropertyFreeSpacePropertyIsReadyPropertyPathPropertySerialNumberPropertyShareNamePropertyTotalSizePropertyVolumeNameProperty
Microsoft®VisualBasic®ScriptingEdition
RootFolderPropertyAppliesTo
ScriptingRun-TimeReference
DriveObject
Microsoft®VisualBasic®ScriptingEdition
SerialNumberPropertySeeAlso
ScriptingRun-TimeReference
AvailableSpacePropertyDriveLetterPropertyDriveTypePropertyFileSystemPropertyFreeSpacePropertyIsReadyPropertyPathPropertyRootFolderPropertyShareNamePropertyTotalSizePropertyVolumeNameProperty
Microsoft®VisualBasic®ScriptingEdition
SerialNumberPropertyAppliesTo
ScriptingRun-TimeReference
DriveObject
Microsoft®VisualBasic®ScriptingEdition
ShareNamePropertySeeAlso
ScriptingRun-TimeReference
AvailableSpacePropertyDriveLetterPropertyDriveTypePropertyFileSystemPropertyFreeSpacePropertyIsReadyPropertyPathPropertyRootFolderPropertySerialNumberPropertyTotalSizePropertyVolumeNameProperty
Microsoft®VisualBasic®ScriptingEdition
ShareNamePropertyAppliesTo
ScriptingRun-TimeReference
DriveObject
Microsoft®VisualBasic®ScriptingEdition
ShortNamePropertySeeAlso
ScriptingRun-TimeReference
AttributesPropertyDateCreatedPropertyDateLastAccessedPropertyDateLastModifiedPropertyDrivePropertyFilesPropertyIsRootFolderPropertyNamePropertyParentFolderPropertyPathPropertyShortPathPropertySizePropertySubFoldersPropertyTypeProperty
Microsoft®VisualBasic®ScriptingEdition
ShortNamePropertyAppliesTo
ScriptingRun-TimeReference
FileObjectFolderObject
Microsoft®VisualBasic®ScriptingEdition
ShortPathPropertySeeAlso
ScriptingRun-TimeReference
AttributesPropertyDateCreatedPropertyDateLastAccessedPropertyDateLastModifiedPropertyDrivePropertyFilesPropertyIsRootFolderPropertyNamePropertyParentFolderPropertyPathPropertyShortNamePropertySizePropertySubFoldersPropertyTypeProperty
Microsoft®VisualBasic®ScriptingEdition
ShortPathPropertyAppliesTo
ScriptingRun-TimeReference
FileObjectFolderObject
Microsoft®VisualBasic®ScriptingEditionSizePropertySeeAlso
ScriptingRun-TimeReference
AttributesPropertyDateCreatedPropertyDateLastAccessedPropertyDateLastModifiedPropertyDrivePropertyFilesPropertyIsRootFolderPropertyNamePropertyParentFolderPropertyPathPropertyShortNamePropertyShortPathPropertySubFoldersPropertyTypeProperty
Microsoft®VisualBasic®ScriptingEditionSizePropertyAppliesTo
ScriptingRun-TimeReference
FileObjectFolderObject
Microsoft®VisualBasic®ScriptingEditionSkipMethodSeeAlso
ScriptingRun-TimeReference
CloseMethodReadMethodReadAllMethodReadLineMethodSkipLineMethodWriteMethodWriteLineMethodWriteBlankLinesMethod
Microsoft®VisualBasic®ScriptingEditionSkipMethodAppliesTo
ScriptingRun-TimeReference
TextStreamObject
Microsoft®VisualBasic®ScriptingEdition
SkipLineMethodSeeAlso
ScriptingRun-TimeReference
CloseMethodReadMethodReadAllMethodReadLineMethodSkipMethodWriteMethodWriteLineMethodWriteBlankLinesMethod
Microsoft®VisualBasic®ScriptingEdition
SkipLineMethodAppliesTo
ScriptingRun-TimeReference
TextStreamObject
Microsoft®VisualBasic®ScriptingEdition
SpecialFolderConstantsSeeAlso
ScriptingRun-TimeReference
ComparisonConstantsDriveTypeConstantsFileAttributeConstantsFileInput/OutputConstantsTristateConstants
Microsoft®VisualBasic®ScriptingEdition
SubFoldersPropertySeeAlso
ScriptingRun-TimeReference
AttributesPropertyDateCreatedPropertyDateLastAccessedPropertyDateLastModifiedPropertyDrivePropertyFilesPropertyIsRootFolderPropertyNamePropertyParentFolderPropertyPathPropertyShortNamePropertyShortPathPropertySizePropertyTypeProperty
Microsoft®VisualBasic®ScriptingEdition
SubFoldersPropertyAppliesTo
ScriptingRun-TimeReference
FolderObject
Microsoft®VisualBasic®ScriptingEdition
TextStreamObjectSeeAlso
ScriptingRun-TimeReference
DictionaryObjectFileSystemObjectObject
Microsoft®VisualBasic®ScriptingEdition
TextStreamObjectProperties
ScriptingRun-TimeReference
AtEndOfLinePropertyAtEndOfStreamPropertyColumnPropertyLineProperty
Microsoft®VisualBasic®ScriptingEdition
TextStreamObjectMethods
ScriptingRun-TimeReference
CloseMethodReadMethodReadAllMethodReadLineMethodSkipMethodSkipLineMethodWriteMethodWriteLineMethodWriteBlankLinesMethod
Microsoft®VisualBasic®ScriptingEdition
TotalSizePropertySeeAlso
ScriptingRun-TimeReference
AvailableSpacePropertyDriveLetterPropertyDriveTypePropertyFileSystemPropertyFreeSpacePropertyIsReadyPropertyPathPropertyRootFolderPropertySerialNumberPropertyShareNamePropertyVolumeNameProperty
Microsoft®VisualBasic®ScriptingEdition
TotalSizePropertyAppliesTo
ScriptingRun-TimeReference
DriveObject
Microsoft®VisualBasic®ScriptingEditionTypePropertySeeAlso
ScriptingRun-TimeReference
AttributesPropertyDateCreatedPropertyDateLastAccessedPropertyDateLastModifiedPropertyDrivePropertyFilesPropertyIsRootFolderPropertyNamePropertyParentFolderPropertyPathPropertyShortNamePropertyShortPathPropertySizePropertySubFoldersProperty
Microsoft®VisualBasic®ScriptingEditionTypePropertyAppliesTo
ScriptingRun-TimeReference
FileObjectFolderObject
Microsoft®VisualBasic®ScriptingEdition
VolumeNamePropertySeeAlso
ScriptingRun-TimeReference
AvailableSpacePropertyDriveLetterPropertyDriveTypePropertyFileSystemPropertyFreeSpacePropertyIsReadyPropertyPathPropertyRootFolderPropertySerialNumberPropertyShareNamePropertyTotalSizeProperty
Microsoft®VisualBasic®ScriptingEdition
VolumeNamePropertyAppliesTo
ScriptingRun-TimeReference
DriveObject
Microsoft®VisualBasic®ScriptingEditionWriteMethodSeeAlso
ScriptingRun-TimeReference
CloseMethodReadMethodReadAllMethodReadLineMethodSkipMethodSkipLineMethodWriteLineMethodWriteBlankLinesMethod
Microsoft®VisualBasic®ScriptingEditionWriteMethodAppliesTo
ScriptingRun-TimeReference
TextStreamObject
Microsoft®VisualBasic®ScriptingEdition
WriteBlankLinesMethodSeeAlso
ScriptingRun-TimeReference
CloseMethodReadMethodReadAllMethodReadLineMethodSkipMethodSkipLineMethodWriteMethodWriteLineMethod
Microsoft®VisualBasic®ScriptingEdition
WriteBlankLinesMethodAppliesTo
ScriptingRun-TimeReference
TextStreamObject
Microsoft®VisualBasic®ScriptingEdition
WriteLineMethodSeeAlso
ScriptingRun-TimeReference
CloseMethodReadMethodReadAllMethodReadLineMethodSkipMethodSkipLineMethodWriteMethodWriteBlankLinesMethod
Microsoft®VisualBasic®ScriptingEdition
WriteLineMethodAppliesTo
ScriptingRun-TimeReference
TextStreamObject
Microsoft®VisualBasic®ScriptingEdition
InStrRevFunctionSeeAlso
LanguageReference
InStrFunction
Microsoft®VisualBasic®ScriptingEdition
ArithmeticOperators
LanguageReferenceVersion1
^Operator*Operator/Operator\OperatorModOperator+Operator-OperatorConcatenationOperators
Microsoft®VisualBasic®ScriptingEdition
ConcatenationOperators
LanguageReferenceVersion1
&Operator+Operator
Microsoft®VisualBasic®ScriptingEdition
OperatorSummary
LanguageReferenceVersion1
SeeAlso
ArithmeticOperators
Operatorsusedtoperformmathematicalcalculations.
AssignmentOperator
Operatorusedtoassignavaluetoapropertyorvariable.
ComparisonOperators
Operatorsusedtoperformcomparisons.
ConcatenationOperators
Operatorsusedtocombinestrings.
LogicalOperators
Operatorsusedtoperformlogicaloperations.
Microsoft®VisualBasic®ScriptingEditionLogicalOperators
LanguageReferenceVersion1
AndOperatorNotOperatorOrOperatorXorOperator
Microsoft®VisualBasic®ScriptingEditionDerivedMathFunctions
LanguageReferenceVersion1
SeeAlso
Description
Thefollowingnonintrinsicmathfunctionscanbederivedfromtheintrinsicmathfunctions:
Function DerivedequivalentsSecant Sec(X)=1/Cos(X)Cosecant Cosec(X)=1/Sin(X)Cotangent Cotan(X)=1/Tan(X)InverseSine Arcsin(X)=Atn(X/Sqr(-X*X+1))
InverseCosine Arccos(X)=Atn(-X/Sqr(-X*X+1))+2*Atn(1)
InverseSecant Arcsec(X)=Atn(X/Sqr(X*X-1))+Sgn((X)-1)*(2*Atn(1))
InverseCosecant Arccosec(X)=Atn(X/Sqr(X*X-1))+(Sgn(X)-1)*(2*Atn(1))
InverseCotangent Arccotan(X)=Atn(X)+2*Atn(1)HyperbolicSine HSin(X)=(Exp(X)-Exp(-X))/2HyperbolicCosine HCos(X)=(Exp(X)+Exp(-X))/2HyperbolicTangent
HTan(X)=(Exp(X)-Exp(-X))/(Exp(X)+Exp(-X))
HyperbolicSecant HSec(X)=2/(Exp(X)+Exp(-X))HyperbolicCosecant HCosec(X)=2/(Exp(X)-Exp(-X))
Hyperbolic HCotan(X)=(Exp(X)+Exp(-X))/(Exp(X)
Cotangent -Exp(-X))InverseHyperbolicSine HArcsin(X)=Log(X+Sqr(X*X+1))
InverseHyperbolicCosine HArccos(X)=Log(X+Sqr(X*X-1))
InverseHyperbolicTangent HArctan(X)=Log((1+X)/(1-X))/2
InverseHyperbolicSecant
HArcsec(X)=Log((Sqr(-X*X+1)+1)/X)
InverseHyperbolicCosecant
HArccosec(X)=Log((Sgn(X)*Sqr(X*X+1)+1)/X)
InverseHyperbolicCotangent HArccotan(X)=Log((X+1)/(X-1))/2
LogarithmtobaseN LogN(X)=Log(X)/Log(N)
Microsoft®VisualBasic®ScriptingEdition
VBScriptErrorMessages
LanguageReference
ErrorCode Message
5 Invalidprocedurecallorargument6 Overflow7 Outofmemory9 Subscriptoutofrange10 Arrayfixedortemporarilylocked11 Divisionbyzero13 Typemismatch14 Outofstringspace28 Outofstackspace35 SuborFunctionnotdefined48 ErrorinloadingDLL51 Internalerror53 Filenotfound57 DeviceI/Oerror58 Filealreadyexists61 Diskfull67 Toomanyfiles70 Permissiondenied75 Path/Fileaccesserror76 Pathnotfound91 ObjectvariableorWithblockvariablenotset
92 Forloopnotinitialized94 InvaliduseofNull322 Can'tcreatenecessarytemporaryfile424 Objectrequired429 ActiveXcomponentcan'tcreateobject430 Classdoesn'tsupportAutomation
432 FilenameorclassnamenotfoundduringAutomationoperation
438 Objectdoesn'tsupportthispropertyormethod440 Automationerror445 Objectdoesn'tsupportthisaction446 Objectdoesn'tsupportnamedarguments447 Objectdoesn'tsupportcurrentlocalesetting448 Namedargumentnotfound449 Argumentnotoptional
450 Wrongnumberofargumentsorinvalidpropertyassignment
451 Objectnotacollection453 SpecifiedDLLfunctionnotfound455 Coderesourcelockerror
457 Thiskeyalreadyassociatedwithanelementofthiscollection
458 VariableusesanAutomationtypenotsupportedinVBScript
500 Variableisundefined501 Illegalassignment502 Objectnotsafeforscripting503 Objectnotsafeforinitializing1001 Outofmemory1002 Syntaxerror1003 Expected':'
1004 Expected';'
1005 Expected'('1006 Expected')'1007 Expected']'1008 Expected'{'1009 Expected'}'1010 Expectedidentifier1011 Expected'='1012 Expected'If'1013 Expected'To'1014 Expected'End'1015 Expected'Function'1016 Expected'Sub'1017 Expected'Then'1018 Expected'Wend'1019 Expected'Loop'1020 Expected'Next'1021 Expected'Case'1022 Expected'Select'1023 Expectedexpression1024 Expectedstatement1025 Expectedendofstatement1026 Expectedintegerconstant1027 Expected'While'or'Until'1028 Expected'While','Until',orendofstatement1029 Toomanylocalsorarguments1030 Identifiertoolong1031 Invalidnumber1032 Invalidcharacter
1033 Unterminatedstringconstant1034 Unterminatedcomment
1035 Nestedcomment1037 Invaliduseof'Me'keyword1038 'Loop'without'Do'1039 Invalid'Exit'statement1040 Invalid'For'loopcontrolvariable1041 Nameredefined1042 Mustbefirststatementontheline1043 Can'tassigntonon-ByValargument1044 Can'tuseparenswhencallingaSub1045 Expectedliteralconstant1046 Expected'In'32766 True32767 False32811 Elementnotfound
Microsoft®VisualBasic®ScriptingEdition
WeekdayNameFunction
LanguageReferenceVersion2
SeeAlso
Description
Returnsastringindicatingthespecifieddayoftheweek.
Syntax
WeekdayName(weekday,abbreviate,firstdayofweek)
TheWeekdayNamefunctionsyntaxhastheseparts:
Part Description
weekdayRequired.Thenumericdesignationforthedayoftheweek.Numericvalueofeachdaydependsonsettingofthefirstdayofweeksetting.
abbreviate
Optional.Booleanvaluethatindicatesiftheweekdaynameistobeabbreviated.Ifomitted,thedefaultisFalse,whichmeansthattheweekdaynameisnotabbreviated.
firstdayofweek Optional.Numericvalueindicatingthefirstdayoftheweek.SeeSettingssectionforvalues.
Settings
Thefirstdayofweekargumentcanhavethefollowingvalues:
Constant Value Description
vbUseSystem 0 UseNationalLanguageSupport(NLS)APIsetting.
vbSunday 1 Sunday(default)
vbMonday 2 MondayvbTuesday 3 TuesdayvbWednesday 4 WednesdayvbThursday 5 ThursdayvbFriday 6 FridayvbSaturday 7 Saturday
Remarks
ThefollowingexampleusestheWeekDayNamefunctiontoreturnthespecifiedday:
DimMyDateMyDate=WeekDayName(6,True)'MyDatecontainsFri.
Microsoft®VisualBasic®ScriptingEdition
ExecuteGlobalStatementSeeAlso
LanguageReference
EvalFunctionExecuteStatement
Microsoft®VisualBasic®ScriptingEdition
GetLocaleFunctionSeeAlso
LanguageReference
SetLocaleFunctionLocaleID(LCID)Chart
Microsoft®VisualBasic®ScriptingEditionLocaleID(LCID)ChartSeeAlso
LanguageReference
GetLocaleFunctionSetLocaleFunction
Microsoft®VisualBasic®ScriptingEdition
SetLocaleFunctionSeeAlso
LanguageReference
GetLocaleFunctionLocaleID(LCID)Chart
Microsoft®VisualBasic®ScriptingEdition
OperatorSummarySeeAlso
LanguageReference
OperatorPrecedence
Microsoft®VisualBasic®ScriptingEdition
AssignmentOperator
LanguageReferenceVersion1
=Operator
Microsoft®VisualBasic®ScriptingEditionDerivedMathFunctionsSeeAlso
LanguageReference
AtnFunctionCosFunctionExpFunctionLogFunctionSinFunctionSqrFunctionTanFunction
Microsoft®VisualBasic®ScriptingEdition
WeekdayNameFunctionSeeAlso
LanguageReference
MonthNameFunction