Documente Academic
Documente Profesional
Documente Cultură
VB6/VBA/OfficeTip:HowtorenameaFileorFolder(Directory)inCode
Thu18Jun2015
Jump:
Search:
Like
Tweet
Go
MicrosoftAccess
DeveloperCenter
HowtoRenameaFileorFolder(Directory)fromVBA,VisualBasic6,Microsoft
Office/Access/Excel
StrategicOverview
Providedby:FMSDevelopmentTeam
MicrosoftAccesswithinan
Organization'sDatabase
Strategy
MicrosoftAccessvs.Excel
Howmanysimultaneous
MicrosoftAccessusers?
BlamingMicrosoftAccess
insteadoftheDeveloper
HistoryofAccess
MicrosoftAccessVersions,
ServicePacksandUpdates
HowAccessStarted
MicrosoftAccessandOffice
2010SP2Issues
Top14FeaturesAdded
withMSAccess2007
BestPractices
TakingOverLegacyMS
AccessDatabases
100+PerformanceTips
DidyouknowthereisabuiltinstatementinVB6/VBA/Office/Access/ExcelthatallowsyoutodothiswithoutusingAPI
callsandwithoutreferencingtheFileSystem?
FromtheVB6,VBA,Office/Access/ExcelHelpFile
TheNamestatementmovesthefiletothenewdirectoryorfolderandrenamesthefile,ifnecessary.Here'sthesyntax:
NameOldPathNameAsNewPathName
Namecanmoveafileacrossdrives,butitcanonlyrenameanexistingdirectoryorfolderwhenbothOldPathNameand
NewPathNamearelocatedonthesamedrive.Namecannotcreateanewfile,directory,orfolder.
IfOldPathNameandNewPathNamehavedifferentpaths,andthesamefilename,theNamestatementmovesthefileto
thenewlocationandleavesthefilenameunchanged.
UsingName,youcanmoveafilefromonedirectoryorfoldertoanother,butyoucannotmoveadirectoryorfolder.
UsingNameonanopenfileproducesanerror.Youmustcloseanopenfilebeforerenamingit.Nameargumentscannot
includemultiplecharacter(*)andsinglecharacter(?)wildcards.
SampleCodeforRenamingaFileorFolder
Ourexamplebelowonlyprovidessupportforfilesorsimplefolderrenaming(e.g.thepathfolderdoesnotexist).
Renamingadirectorytoanamethatalreadyexistsismorecomplicatedandmaybeincludedinafuturetip.
WinnerofEveryBestAccess
AddinAward
SplitDatabase
ArchitectureforMultiuser
FindandDeleteUnused
ObjectsandVBACode
TableDesign
DesigningPrimaryKeys
FieldTypeConsistency
TableNormalizationTips
TakingTimeintoAccount
TemporaryData
TransposingData
SetAutoNumberStarting
NumberOtherthan1
AvoidUnnecessaryor
DuplicateIndexes
ReplaceAttachmentField
PaperclipIcon
AvoidDecimalDataTypes
QueryDesign
MicrosoftAccessQueryTips
andTechniques
FormDesign
FormTipsandMistakes
FormNavigationCaption
UsingaRecordsetClone
SynchronizeTwoSubforms
MultipleOpenArgsValues
LateBindTabSubforms
SubformReferenceto
ControlRatherthanField
TabPageReference
ShortcutKeys
ComboBoxTopTips
PropertiesandValidation
SelectFirstItem
CascadingComboBoxes
PublicFunctionTestNameStatement()
DimfOKAsBoolean
'FoldersmustexistforSource,butdonotneedtoexistfordestination
fOK=RenameFileOrDir("C:\TestFolder\test.txt","C:\TestFolder\test_NEWNAME.txt")
fOK=RenameFileOrDir("C:\TestFolder\test.txt","D:\TestFolder\test_NEWNAME.txt")
'Foldermustexistforsource
fOK=RenameFileOrDir("C:\TestFolder","C:\TestFolder_NEWNAME")
'Foldersonlywillfailacrossdrives
fOK=RenameFileOrDir("C:\TestFolder","D:\TestFolder")
EndFunction
PublicFunctionRenameFileOrDir(ByValstrSourceAsString,ByValstrTargetAsString,_
OptionalfOverwriteTargetAsBoolean=False)AsBoolean
OnErrorGoToPROC_ERR
DimfRenameOKAsBoolean
DimfRemoveTargetAsBoolean
DimstrFirstDriveAsString
DimstrSecondDriveAsString
DimfOKAsBoolean
IfNot((Len(strSource)=0)Or(Len(strTarget)=0)Or(Not(FileOrDirExists(strSource))))Then
'Checkifthetargetexists
IfFileOrDirExists(strTarget)Then
IffOverwriteTargetThen
fRemoveTarget=True
Else
IfMsgBox("Doyouwishtooverwritethetargetfile?",vbExclamation+vbYesNo,"Overwriteconfirmation")=vbYesThen
fRemoveTarget=True
EndIf
EndIf
IffRemoveTargetThen
'Checkthatit'snotadirectory
If((GetAttr(strTarget)AndvbDirectory))<>vbDirectoryThen
KillstrTarget
fRenameOK=True
Else
MsgBox"Cannotoverwriteadirectory",vbOKOnly,"Cannotperformoperation"
EndIf
EndIf
Else
'Thetargetdoesnotexist
'Checkifsourceisadirectory
If((GetAttr(strSource)AndvbDirectory)=vbDirectory)Then
'Sourceisadirectory,seeifdrivesarethesame
strFirstDrive=Left(strSource,InStr(strSource,":\"))
strSecondDrive=Left(strTarget,InStr(strTarget,":\"))
IfstrFirstDrive=strSecondDriveThen
fRenameOK=True
http://www.fmsinc.com/microsoftaccess/modules/examples/rename_file_folder.htm
1/3
6/18/2015
VB6/VBA/OfficeTip:HowtorenameaFileorFolder(Directory)inCode
Zip,City,StateAutoFill
Else
MsgBox"Cannotrenamedirectoriesacrossdrives",vbOKOnly,"Cannotperformoperation"
ReportDesign
EndIf
Else
SuppressingPageHeaders
'It'safile,oktoproceed
andFootersontheFirst
PageofYourReport
fRenameOK=True
EndIf
AddtheNoDataEvent
EndIf
AnnualMonthlyCrosstab
Columns
IffRenameOKThen
DesignEnvironment
NamestrSourceAsstrTarget
fOK=True
AddingButtonstothe
EndIf
QuickAccessToolbar
EndIf
CollapsingtheOffice
Ribbonformorespace
RenameFileOrDir=fOK
VBAProgramming
PROC_EXIT:
UsingNz()toHandleNulls
ExitFunction
AvoidingExitsintheBody
PROC_ERR:
ofaProcedure
MsgBox"Error:"&Err.Number&"."&Err.Description,,"RenameFileOrDir"
ShortcutDebuggingKeys
ResumePROC_EXIT
SettingModuleOptions
EndFunction
MathRoundingIssues
RenameaFileorFolder
AvoidDoEventsinLoops
AgeCalculations
WeekdayMath
SendingEmailswith
DoCmd.SendObject
SourceCodeLibrary
MicrosoftAccessModules
VBAErrorHandling
ErrorHandlingand
DebuggingTechniques
ErrorNumberand
DescriptionReference
BasicErrorHandling
PinpointingtheErrorLine
PerformanceTips
PublicFunctionFileOrDirExists(strDestAsString)AsBoolean
DimintLenAsInteger
DimfReturnAsBoolean
fReturn=False
IfstrDest<>vbNullStringThen
OnErrorResumeNext
intLen=Len(Dir$(strDest,vbDirectory+vbNormal))
OnErrorGoToPROC_ERR
fReturn=(NotErrAndintLen>0)
EndIf
PROC_EXIT:
FileOrDirExists=fReturn
ExitFunction
PROC_ERR:
MsgBox"Error:"&Err.Number&"."&Err.Description,,"FileOrDirExists"
ResumePROC_EXIT
EndFunction
ForotherVBAandVB6SourceCode,checkoutourTotalVisualSourceBookcodelibrarywithroyaltyfreecodeyoucan
addtoyourapplications.
LinkedDatabase
SubdatasheetName
VisualSourceSafe
Deployment
RuntimeDownloads
SimulatingRuntime
PreventCloseBox
DisableDesignChanges
BrokenReferences
MissingPackage&
DeploymentWizard
TerminalServicesand
RemoteAppDeployment
AvoidProgramFilesFolder
SystemAdmin
DisasterRecoveryPlan
CompactDatabase
CompactonClose
DatabaseCorruption
ClassNotRegisteredRun
timeError2147221164
InconsistentCompileError
DecompileDatabase
BadDLLCallingConvention
Error3045:CouldNotUse
ConvertingACCDBtoMDB
SQLServerUpsizing
MicrosoftAccesstoSQL
http://www.fmsinc.com/microsoftaccess/modules/examples/rename_file_folder.htm
2/3
6/18/2015
VB6/VBA/OfficeTip:HowtorenameaFileorFolder(Directory)inCode
ServerUpsizingCenter
WhenandHowtoUpsize
AccesstoSQLServer
SQLServerExpress
VersionsandDownloads
CloudandAzure
CloudImplications
MSAccessandSQLAzure
DeployingMSAccess
LinkedtoSQLAzure
VisualStudio
LightSwitch
LightSwitchIntroduction
ComparisonMatrix
AdditionalResources
MicrosoftAccessHelp
MSAccessDeveloper
Programming
MoreMicrosoftAccessTips
TechnicalPapers
MicrosoftAccessTools
ConnectwithUs
EmailNewsletter
DeveloperTeamBlog
Facebook(Feed)
Twitter
SupportForum
ContactUslWebquestions:WebmasterlCopyrightFMS,Inc.,Vienna,Virginia
Celebratingour28thYearofSoftwareExcellence
http://www.fmsinc.com/microsoftaccess/modules/examples/rename_file_folder.htm
3/3