Rigid file manipulation functions for VBA/VBS
Friday, December 14th, 2007Ever since starting work I have been learning and using VBA/VBS to make life easier. I will start posting some of my generic functions as a source for others. They may not be written optimally, but they do work.
' Function: fileExist(sPathFile) returns True if a file exists
' Input: sPathFile - the file (including path) to determine if exists
' Output: fileExists - returns true if file exists
' Notes: network shared drives work as well.
Function fileExist(sPathFile) As Boolean
On Error Resume Next
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fileExist = fso.FileExists(sPathFile)
Set fso = Nothing
End Function
' Function: renameFile(oldName, newName) renames a file, can also be used to move a file
' Inputs: oldName - file including path to be renamed
' newName - file including path of the renamed or moved file
' Notes: renameFile checks if the file exists and the new path exists before renaming or moving
' Dependants: fileExists
Function renameFile(oldName, newName)
On Error Resume Next
If fileExist(oldName) And Dir(Left(newName, InStrRev(newName, "/")), vbDirectory) <> vbNullString Then
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fso.MoveFile oldName, newName
Set fso = Nothing
End If
End Function
' Function: deleteFile(sPathFile) deletes a file
' Input: sPathFile - the file (including path) to be deleted i.e. "C:/a.txt"
' Notes: deleteFile checks if the file exists first before deleting
' Dependants: deleteFile
Function deleteFile(sPathFile)
On Error Resume Next
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(sPathFile) Then fso.GetFile(sPathFile).Delete
Set fso = Nothing
End Function
' Function: copyFile(fileName, copyName) copies a file
' Inputs: fileName - file to be copied, path and file required i.e. "C:/a.txt"
' copyName - the copied file, path and file required i.e. "C:/b.txt"
' Notes: copyFile checks if fileName exists, as well as the copyName folder
' if copyName is already present the file is deleted
' Dependants: fileExists, deleteFile
Function copyFile(fileName, copyName)
On Error Resume Next
If fileExist(fileName) And Dir(Left(copyName, InStrRev(copyName, "/")), vbDirectory) <> vbNullString Then
Call deleteFile(copyName)
Dim fso
Dim aFile
Set fso = CreateObject("Scripting.FileSystemObject")
fso.copyFile fileName, copyName, True
Set aFile = fso.GetFile(copyName)
If aFile.Attributes And 1 Then
aFile.Attributes = aFile.Attributes - 1
End If
Set fso = Nothing
Set aFile = Nothing
End If
End Function