'********************************************************************************************************** ' Name: printToTextFile ' Author: mielk | 2012-12-06 ' ' Comment: Function to print the given content (String or array) into the specified textfile. ' ' Parameters: ' content Content to be printed out in a textfile. ' filepath The path of a textfile in which the given content should be printed. ' override Optional parameter. ' Determines if the given content should be appended to the existing content of this ' textfile or if it should override this content. ' ' Returns: ' Boolean True - if the given content has been successfully printed. ' False - if any exception has been thrown when trying to print the content into the ' specified filetext. ' ' Exceptions: ' ObjectException Thrown if the [content] parameter is an object. ' ' DimensionsException Thrown if the given array has not given dimensions yet or its number of ' dimensions is greater than 2. ' ' NoAccessToPathException Thrown if the user cannot write into the specified filepath (i.e. he ' has no write-access to this path or it doesn't exist). ' ' FolderCreatingException Thrown if it is impossible to create the parent folder for the ' specified filepath. ' ' ' --- Changes log ----------------------------------------------------------------------------------------- ' 2012-12-06 mielk Function created. '********************************************************************************************************** Public Function printToTextFile(content As Variant, filepath As String, _ Optional override As Boolean = False) As Boolean Const METHOD_NAME As String = "printToTextFile" '------------------------------------------------------------------------------------------------------ 'Checks if [content] parameter is not an object, since objects cannot be printed. If VBA.IsObject(content) Then GoTo ObjectException 'Check if the current user has the write access for the specified path. If Not isTextfileWriteable(filepath) Then GoTo NoAccessToPathException 'Create parent folder for the textfile if it is not created yet. If it cannot be created, 'FolderCreatingException is thrown. If createFolder(getParentFolder(filepath)) Is Nothing Then GoTo FolderCreatingException 'If the parameter [override] is set to True, method deletes the current textfile '(if this textfile exists). This textfile will be created from scratch later on. If override Then Call deleteFile(filepath) 'Printing methods are different for arrays and primitive values. ------------------------------------| If IsArray(content) Then '| '| 'There are different printing subroutines for 1D arrays and 2D arrays. ----------------------| '| 'The [Select Case] statement below checks how many dimensions the given array has '| '| 'and invokes the appropriate subroutine based on that value. '| '| Select Case countDimensions(content) '| '| Case 1: Call printToTextFile_1DArray(content, filepath) '| '| Case 2: Call printToTextFile_2DArray(content, filepath) '| '| Case Else '| '| 'It is impossible to print an array if it is not defined yet or if it '| '| 'has more than two dimensions. In this case DimensionsException is thrown. '| '| GoTo DimensionsException '| '| End Select '| '| '--------------------------------------------------------------------------------------------| '| '| Else '| '| 'If the given content is not an array nor object, it must be primitive. '| 'In this case printToTextFile_primitiveValues subroutine is invoked. '| Call printToTextFile_primitiveValues(content, filepath) '| '| End If '| '----------------------------------------------------------------------------------------------------| 'The given content has been successfully printed. printToTextFile = True '========================================================================================================== ExitPoint: Exit Function '---------------------------------------------------------------------------------------------------------- ObjectException: '(...) 'Put your own error handling here for a case if the given parameter is object and cannot be printed. GoTo ExitPoint DimensionsException: '(...) 'Put your own error handling here for a case if the given parameter is an array but it is not defined 'yet or it has more than two dimensions ... GoTo ExitPoint NoAccessToPathException: '(...) 'Put your own error handling here for a case when the user has no write access for the destination 'path given as a [filepath] parameter ... GoTo ExitPoint FolderCreatingException: '(...) 'Put your own error handling here for a case when the parent folder of the specified filepath could 'have not been created ... GoTo ExitPoint End Function '********************************************************************************************************** ' Name: printToTextFile_primitiveValues ' ' Description: Submethod to print primitive values to a textfile. '********************************************************************************************************** Private Sub printToTextFile_primitiveValues(content As Variant, filepath As String) Const METHOD_NAME As String = "printToTextFile_primitiveValues" '------------------------------------------------------------------------------------------------------ Dim intFile As Integer '------------------------------------------------------------------------------------------------------ intFile = VBA.FreeFile() Open filepath For Append As #intFile Print #intFile, content Close intFile End Sub '********************************************************************************************************** ' Name: printToTextFile_1DArray ' ' Description: Submethod to print one-dimensional array. '********************************************************************************************************** Private Sub printToTextFile_1DArray(content As Variant, filepath As String) Const METHOD_NAME As String = "printToTextFile_1DArray" '------------------------------------------------------------------------------------------------------ Dim intFile As Integer Dim lngRow As Long '------------------------------------------------------------------------------------------------------ intFile = VBA.FreeFile() Open filepath For Append As #intFile For lngRow = LBound(content, 1) To UBound(content, 1) Print #intFile, content(lngRow) Next lngRow Close intFile End Sub '********************************************************************************************************** ' Name: printToTextFile_2DArray ' ' Description: Submethod to print two-dimensional array to a textfile. '********************************************************************************************************** Private Sub printToTextFile_2DArray(content As Variant, filepath As String) Const METHOD_NAME As String = "printToTextFile_2DArray" 'Constant to define a separator for columns in the array being printed. Const SEPARATOR As String = ";" '------------------------------------------------------------------------------------------------------ Dim intFile As Integer Dim lngRow As Long Dim lngCol As Long Dim strCol As String '------------------------------------------------------------------------------------------------------ intFile = VBA.FreeFile() Open filepath For Append As #intFile For lngRow = LBound(content, 1) To UBound(content, 1) 'Value of the parameter [sCol] is cleared in every iteration 'in order not to store a content from the previous array rows. strCol = "" 'The loop below appends the value of each cell in the particular 'row to [sCol] parameter, separating them from each other with 'a character defined in [SEPARATOR] constant. For lngCol = LBound(content, 2) To UBound(content, 2) strCol = strCol & content(lngRow, lngCol) & SEPARATOR Next lngCol 'Separator appended after the last item is being cut ... If VBA.Len(strCol) Then strCol = VBA.Left$(strCol, VBA.Len(strCol) - 1) End If '... and ultimately the string stored in [sCol] parameter 'is being printed to a textfile. Print #intFile, strCol Next lngRow Close intFile End Sub '********************************************************************************************************** ' Name: isTextfileWriteable ' Author: mielk | 2012-12-02 ' ' Comment: Function to check if it is possible to write data into the specified textfile. ' ' Parameters: ' filepath The path of a file to be checked. ' ' Returns: ' Boolean True - if it is possible to write to a textfile with the given path. ' False - if the folder of the specified textfile doesn't exist or the user has ' not read-write access to it. ' ' ' --- Changes log ----------------------------------------------------------------------------------------- ' 2012-12-02 mielk Function created. '********************************************************************************************************** Public Function isTextfileWriteable(filepath As String) As Boolean Const METHOD_NAME As String = "isTextfileWriteable" 'Define extensions of text files. Dim TEXT_EXTENSIONS As Variant: TEXT_EXTENSIONS = Array("txt", "csv") '------------------------------------------------------------------------------------------------------ Static objFSO As Object '(Late binding that allows to use the function, even if 'Microsoft Scripting Runtime library is not loaded) Dim strDriveName As String Dim strBaseFolder As String Dim strParentFolder As String Dim strExtension As String '------------------------------------------------------------------------------------------------------ 'Create FileSystemObject instance if it hasn't been created yet. ------------------------------------| If objFSO Is Nothing Then '| Set objFSO = VBA.CreateObject("Scripting.FileSystemObject") '| End If '| '----------------------------------------------------------------------------------------------------| With objFSO 'Check if the given textfile exists and if it is read-only. -------------------------------------| If .fileExists(filepath) Then '| '| isTextfileWriteable = Not (VBA.GetAttr(filepath) And VBA.vbReadOnly) '| '| Else '| '| 'Check if the drive from the given filepath exists. -------------------------------------| '| strDriveName = .GetDriveName(filepath) '| '| If .DriveExists(strDriveName) Then '| '| '| '| 'Checks if the extension in the specified filepath is proper for a textfile. ----| '| '| strExtension = .GetExtensionName(filepath) '| '| '| If isInArray(strExtension, TEXT_EXTENSIONS, False) Then '| '| '| '| '| '| 'Retrieve the base folder name and check if it is allowed to add --------| '| '| '| 'subfolders to this folder. '| '| '| '| strParentFolder = .GetParentFolderName(filepath) '| '| '| '| strBaseFolder = .GetParentFolderName(filepath) '| '| '| '| Do Until .FolderExists(strBaseFolder) '| '| '| '| strBaseFolder = .GetParentFolderName(strBaseFolder) '| '| '| '| Loop '| '| '| '| '------------------------------------------------------------------------| '| '| '| '| '| '| '| '| '| '------------------------------------------------------------------------| '| '| '| If VBA.StrComp(strBaseFolder, strParentFolder, vbTextCompare) = 0 Then '| '| '| '| 'Destination folder already exists. '| '| '| '| isTextfileWriteable = isFolderWriteable(strParentFolder) '| '| '| '| Else '| '| '| '| 'Destination folder is yet to be created. '| '| '| '| isTextfileWriteable = isSubfoldersAddingAllowed(strBaseFolder) '| '| '| '| End If '| '| '| '| '------------------------------------------------------------------------| '| '| '| '| '| '| '| '| '| Else '| '| '| '| '| '| 'The extension in the specified filepath is improper. '| '| '| isTextfileWriteable = False '| '| '| '| '| '| End If '| '| '| '---- [If .FileExists(filepath) Then] -------------------------------------------| '| '| '| '| Else '| '| '| '| 'Drive retrieved from the given filepath doesn't exist. '| '| isTextfileWriteable = False '| '| '| '| End If '| '| '-------- [If .FileExists(filepath) Then] -----------------------------------------------| '| '| End If '| '------------ [If .FileExists(filepath) Then] ---------------------------------------------------| End With End Function '********************************************************************************************************** ' Name: isInArray ' Author: mielk | 2011-07-19 ' ' Comment: Checks if a specified value is contained in the given array. ' ' Parameters: ' value String to be checked. ' arr Array to be tested. ' Each item of this array is compared to source value [value] and if any of them is ' equal to this string, function returns True. ' Parameter [arr] has to be a one-dimensional array that contains only values of ' primitive types. If it contain any object, exception ObjectsInArrayException will ' be thrown. ' isCaseSensitive Optional parameter of Boolean type. ' It determines if text comparing is case sensitive. ' If this value is set to True, comparing is case sensitive - a letter in lowercase ' is treated as different than the same letter in uppercase (i.e. a ? A). ' If this value is set to False, it doesn't matter if a letter is in lowercase or in ' uppercase, since both of them are considered as the same character (i.e. a = A). ' Default value of this parameter is False. ' ' Returns: ' Boolean True - if any item of the given array [arr] is equal to the ' specified string [str]. ' False - otherwise. ' ' Exceptions: ' NotArrayException Thrown when the given [arr] parameter is not an array. ' ObjectsInArrayException Thrown when the given array contains not only values of primitive ' types, but also objects. ' ' ' --- Changes log ----------------------------------------------------------------------------------------- ' 2011-07-19 mielk Class created. '********************************************************************************************************** Public Function isInArray(value As String, arr As Variant, _ Optional isCaseSensitive As Boolean = False) As Boolean Const METHOD_NAME As String = "startsWith" Dim SEPARATOR As String: SEPARATOR = VBA.Chr(0) '------------------------------------------------------------------------------------------------------ Dim tempStr As String Dim uCompareMethod As VBA.VbCompareMethod '------------------------------------------------------------------------------------------------------ 'Checks if the given parameter [arr] is an array. If not, code moves to the -------------------------| 'NotArrayException label. '| If countDimensions(arr) <> 1 Then GoTo NotArrayException '| '----------------------------------------------------------------------------------------------------| 'Convert [isCaseSensitive] parameter of Boolean type to the [VbCompareMethod] enumeration. ----------| If isCaseSensitive Then '| uCompareMethod = VBA.vbBinaryCompare '| Else '| uCompareMethod = VBA.vbTextCompare '| End If '| '----------------------------------------------------------------------------------------------------| 'Try to convert the given array into String using VBA-built-in function Join. If there is -----------| 'any object in the given array error will be generated and macro moves to the '| 'ObjectsInArrayException label. '| On Error GoTo ObjectsInArrayException '| tempStr = SEPARATOR & VBA.Join(arr, SEPARATOR) & SEPARATOR '| On Error GoTo 0 '| '----------------------------------------------------------------------------------------------------| isInArray = VBA.InStr(1, tempStr, SEPARATOR & value & SEPARATOR, uCompareMethod) '========================================================================================================== ExitPoint: Exit Function '----------------------------------------------- NotArrayException: '(...) 'Put your own error handling here for a case if the given parameter [arr] is not array. GoTo ExitPoint ObjectsInArrayException: '(...) 'Put your own error handling here for a case if the given array contains any object. GoTo ExitPoint End Function '********************************************************************************************************** ' Name: countDimensions ' Author: mielk | 2012-03-03 ' ' Comment: Returns the number of dimensions of the given VBA array. ' ' Parameters: ' arr Array for which number of dimensions is to be returned. ' ' Returns: ' Integer The number of dimensions of the given VBA array. ' If the given value is not an array function returns -1. ' If the given value is declared as a dynamic array but its dimensions have not been ' declared yet, 0 is returned. ' ' ' --- Changes log ----------------------------------------------------------------------------------------- ' 2012-03-03 mielk Function created. ' 2014-06-15 mielk Returned type changed to Integer to allow -1 to be returned. ' For non-arrays values -1 is returned. '********************************************************************************************************** Public Function countDimensions(arr As Variant) As Integer Const METHOD_NAME As String = "countDimensions" '------------------------------------------------------------------------------------------------------ Dim bound As Long '------------------------------------------------------------------------------------------------------ If VBA.IsArray(arr) Then On Error GoTo NoMoreDimensions Do bound = UBound(arr, countDimensions + 1) countDimensions = countDimensions + 1 Loop Else countDimensions = -1 End If '---------------------------------------------------------------------------------------------------------- NoMoreDimensions: End Function '********************************************************************************************************** ' Name: isFolderWriteable ' Author: mielk | 2012-12-02 ' ' Comment: Function to check if the current user has the rights to add, delete and modify ' files in the specified folder ' ' Parameters: ' folderPath The path of a folder to be checked. ' ' Returns: ' Boolean True - if the given folder exists and the current user has the read-write ' access to this folder. ' False - if the given folder doesn't exist or the user has not read-write ' access to it. ' ' Exceptions: ' FolderNotExistException Thrown if a folder with the specified path doesn't exist. ' ' ' --- Changes log ----------------------------------------------------------------------------------------- ' 2012-12-02 mielk Function created. '********************************************************************************************************** Public Function isFolderWriteable(folderPath As String) As Boolean Const METHOD_NAME As String = "isFolderWriteable" Const TEMP_FILE_NAME As String = "TestFile.txt" '------------------------------------------------------------------------------------------------------ Static objFSO As Object '(Late binding that allows to use the function, even if 'Microsoft Scripting Runtime library is not loaded) Dim strTempFile As String '------------------------------------------------------------------------------------------------------ 'Create FileSystemObject instance if it hasn't been created yet. ------------------------------------| If objFSO Is Nothing Then '| Set objFSO = VBA.CreateObject("Scripting.FileSystemObject") '| End If '| '----------------------------------------------------------------------------------------------------| 'Check if the given folder exists at all. -----------------------------------------------------------| If objFSO.FolderExists(folderPath) Then '| '| 'Create the full path of a temporary file. '| strTempFile = folderPath '| If Not VBA.right$(folderPath, 1) = "\" Then strTempFile = strTempFile & "\" '| strTempFile = uniqueFilePath(strTempFile & TEMP_FILE_NAME) '| '| '| 'Try to create a temporary file. --------------------------------------------------------| '| On Error Resume Next '| '| Call objFSO.CreateTextFile(strTempFile) '| '| On Error GoTo 0 '| '| '----------------------------------------------------------------------------------------| '| '| '| 'Check if temporary file has been created. If it exists, the function should ------------| '| 'return True and delete this file. '| '| If objFSO.fileExists(strTempFile) Then '| '| isFolderWriteable = True '| '| Call objFSO.deleteFile(strTempFile) '| '| End If '| '| '----------------------------------------------------------------------------------------| '| '| Else '| '| GoTo FolderNotExistException '| '| End If '| '-------- [If objFSO.FolderExists(folderPath) Then] -------------------------------------------------| '========================================================================================================== ExitPoint: Exit Function '---------------------------------------------------------------------------------------------------------- FolderNotExistException: '(...) 'Put your own error handling here for a case if the given folder does not exist. GoTo ExitPoint End Function '********************************************************************************************************** ' Name: uniqueFilePath ' Author: mielk | 2012-12-02 ' ' Comment: Function transforms the given filepath so that it is unique in the file system. ' ' Parameters: ' filepath The filepath to be transformed. ' ' Returns: ' String The specified filepath transformed into a unique one. ' If the specified filepath doesn't exist yet, the original name is returned. ' If the file with the specified path already exist, the path returned by the ' function consists of the original filepath and the number in brackets appended ' after the filename. ' ' Example: ' --------------------------------------------------------------------------------- ' If you run this function for filepath C:\test.txt and such file doesn't exist ' yet, the original filepath (C:\test.txt) is returned. ' ' However, if such file already exists, the filepath C:\test (1).txt is returned. ' In case this transformed filepath also exists already, the next number is appended: ' C:\test (2).txt and so on. ' ' ' Please note that the function doesn't check if the given filepath has been ' constructed properly. If the function is invoked with the improper filepath, it is ' just trying to find this file in the file system, but won't find it, since the ' filepath is improper, and will think about it as if it was a unique filepath. ' ' ' --- Changes log ----------------------------------------------------------------------------------------- ' 2012-12-02 mielk Function created. '********************************************************************************************************** Public Function uniqueFilePath(filepath As String) As String Const METHOD_NAME As String = "uniqueFilePath" '------------------------------------------------------------------------------------------------------ Static objFSO As Object '(Late binding that allows to use the function, even if 'Microsoft Scripting Runtime library is not loaded) Dim strFileExtension As String Dim strFileName As String Dim strParentFolder As String Dim strTempFilePath As String Dim intCounter As Integer '------------------------------------------------------------------------------------------------------ 'Create FileSystemObject instance if it hasn't been created yet. ------------------------------------| If objFSO Is Nothing Then '| Set objFSO = VBA.CreateObject("Scripting.FileSystemObject") '| End If '| '----------------------------------------------------------------------------------------------------| With objFSO 'Checks if the file already exists. -------------------------------------------------------------| If .fileExists(filepath) Then '| '| 'If the given filepath already exists, function transforms its name by '| 'appending the number in brackets. '| strParentFolder = .GetParentFolderName(filepath) '| If Not VBA.right$(strParentFolder, 1) = "\" Then strParentFolder = strParentFolder & "\" '| strFileName = .GetBaseName(filepath) '| strFileExtension = "." & .GetExtensionName(filepath) '| '| '------------------------------------------------------------------------------------| '| Do '| '| intCounter = intCounter + 1 '| '| strTempFilePath = strParentFolder & strFileName & _ " (" & intCounter & ")" & strFileExtension '| '| Loop While .fileExists(strTempFilePath) '| '| '------------------------------------------------------------------------------------| '| '| uniqueFilePath = strTempFilePath '| '| Else '| '| 'Specified filepath is unique in the file system and is returned in its original form. '| uniqueFilePath = filepath '| '| End If '| '-------- [If .FileExists(filepath) Then] -------------------------------------------------------| End With End Function '********************************************************************************************************** ' Name: isSubfoldersAddingAllowed ' Author: mielk | 2012-12-02 ' ' Comment: Function to check if the current user has the rights to add subfolders to the ' specified folder. ' ' Parameters: ' folderPath The path of a folder to be checked. ' ' Returns: ' Boolean True - if the given folder exists and the current user has the rights to add ' subfolder to this folder. ' False - otherwise. ' ' Exceptions: ' FolderNotExistException Thrown if a folder with the specified path doesn't exist. ' ' ' --- Changes log ----------------------------------------------------------------------------------------- ' 2012-12-02 mielk Function created. '********************************************************************************************************** Public Function isSubfoldersAddingAllowed(folderPath As String) As Boolean Const METHOD_NAME As String = "isSubfoldersAddingAllowed" Const SUBFOLDER_NAME As String = "TestFolder" '------------------------------------------------------------------------------------------------------ Static objFSO As Object '(Late binding that allows to use the function, even if 'Microsoft Scripting Runtime library is not loaded) Dim strTempFolder As String '------------------------------------------------------------------------------------------------------ 'Create FileSystemObject instance if it hasn't been created yet. ------------------------------------| If objFSO Is Nothing Then '| Set objFSO = VBA.CreateObject("Scripting.FileSystemObject") '| End If '| '----------------------------------------------------------------------------------------------------| 'Check if the given folder exists at all. -----------------------------------------------------------| If objFSO.FolderExists(folderPath) Then '| '| 'Create the full path of a temporary folder. '| strTempFolder = folderPath '| If Not VBA.right$(folderPath, 1) = "\" Then strTempFolder = strTempFolder & "\" '| strTempFolder = uniqueFolderName(strTempFolder & SUBFOLDER_NAME) '| '| 'Try to create a temporary folder. ------------------------------------------------------| '| On Error Resume Next '| '| Call objFSO.createFolder(strTempFolder) '| '| On Error GoTo 0 '| '| '----------------------------------------------------------------------------------------| '| '| 'Check if temporary folder has been created. If it exists, the function should ----------| '| 'return True and delete this folder. '| '| If objFSO.FolderExists(strTempFolder) Then '| '| isSubfoldersAddingAllowed = True '| '| Call objFSO.deleteFolder(strTempFolder) '| '| End If '| '| '----------------------------------------------------------------------------------------| '| '| Else '| '| GoTo FolderNotExistException '| '| End If '| '-------- [If objFSO.FolderExists(folderPath) Then] -------------------------------------------------| '========================================================================================================== ExitPoint: Exit Function '---------------------------------------------------------------------------------------------------------- FolderNotExistException: '(...) 'Put your own error handling here for a case if the given folder does not exist. GoTo ExitPoint End Function '********************************************************************************************************** ' Name: uniqueFolderName ' Author: mielk | 2012-12-02 ' ' Comment: Function transforms the given folder name so that it is unique in its ' parent folder. ' ' Parameters: ' folderName The name of the folder to be transformed. ' ' Returns: ' String The specified folder name transformed into a unique one. ' If the parent folder doesn't containt the folder with such name, the original name ' is returned. ' If the folder with the specified name already exists in the parental folder, the ' number in brackets is appended to the given folder name. ' ' Example: ' --------------------------------------------------------------------------------- ' If you run the function for the folder name C:\folders\test and its parental ' folder (C:\folders\) doesn't contain any folder with this name, the original ' name (C:\folders\test) is returned. ' ' However, if the parental folder already contains a folder with this name, the name ' C:\folders\ test (1) is returned. ' In case this transformed name also exists already, the next number is appended: ' C:\folders\test (2), and so on. ' ' ' --- Changes log ----------------------------------------------------------------------------------------- ' 2012-12-02 mielk Function created. '********************************************************************************************************** Public Function uniqueFolderName(folderName As String) As String Const METHOD_NAME As String = "uniqueFolderName" '------------------------------------------------------------------------------------------------------ Static objFSO As Object '(Late binding that allows to use the function, even if 'Microsoft Scripting Runtime library is not loaded) Dim strFolderName As String Dim strParentFolder As String Dim strTempName As String Dim intCounter As Integer '------------------------------------------------------------------------------------------------------ 'Create FileSystemObject instance if it hasn't been created yet. ------------------------------------| If objFSO Is Nothing Then '| Set objFSO = VBA.CreateObject("Scripting.FileSystemObject") '| End If '| '----------------------------------------------------------------------------------------------------| With objFSO 'Checks if the folder already exists. -----------------------------------------------------------| If .FolderExists(folderName) Then '| '| 'If the given folder name already exists, function transforms its name by '| 'appending the number in brackets. '| strParentFolder = .GetParentFolderName(folderName) '| If Not VBA.right$(strParentFolder, 1) = "\" Then strParentFolder = strParentFolder & "\" '| strFolderName = .GetBaseName(folderName) '| '| '------------------------------------------------------------------------------------| '| Do '| '| intCounter = intCounter + 1 '| '| strTempName = strParentFolder & strFolderName & " (" & intCounter & ")" '| '| Loop While .FolderExists(strTempName) '| '| '------------------------------------------------------------------------------------| '| '| uniqueFolderName = strTempName '| '| Else '| '| 'The given folder name is unique in the file system and is returned in its '| 'original form. '| uniqueFolderName = folderName '| '| End If '| '-------- [If .FolderExists(folderName) Then] ---------------------------------------------------| End With End Function '********************************************************************************************************** ' Name: createFolder ' Author: mielk | 2012-12-02 ' ' Comment: Function to create and return the reference to the specified folder. ' ' Parameters: ' folderPath The path of a folder to be returned. ' ' Returns: ' Object Object of a Scripting.Folder type representing a folder with the specified path. ' ' If the folder already exists, the function returns just the reference to it ' without taking any additional actions. ' ' If the folder doesn't exists, the function creates it and returns the reference ' to this folder. ' ' If the folder cannot be created (i.e. access is denied or the specified folderPath ' is incorrect) Nothing is returned. ' ' ' --- Changes log ----------------------------------------------------------------------------------------- ' 2012-12-02 mielk Function created. '********************************************************************************************************** Public Function createFolder(folderPath As String) As Object Const METHOD_NAME As String = "createFolder" '------------------------------------------------------------------------------------------------------ Static objFSO As Object '(Late binding that allows to use the function, even if 'Microsoft Scripting Runtime library is not loaded) Dim strDriveName As String Dim strParentFolder As String '------------------------------------------------------------------------------------------------------ 'Create FileSystemObject instance if it hasn't been created yet. ------------------------------------| If objFSO Is Nothing Then '| Set objFSO = VBA.CreateObject("Scripting.FileSystemObject") '| End If '| '----------------------------------------------------------------------------------------------------| With objFSO 'If the given folder already exists, it is just assigned to the variable [createFolder] and -----| 'returned as the result of the function. '| If .FolderExists(folderPath) Then '| '| Set createFolder = .getFolder(folderPath) '| '| Else '| '| 'Check if the drive from the given filepath exists. -------------------------------------| '| strDriveName = .GetDriveName(folderPath) '| '| If .DriveExists(strDriveName) Then '| '| '| '| 'Retrieve the parent folder name. -----------------------------------------------| '| '| strParentFolder = .GetParentFolderName(folderPath) '| '| '| If Not .FolderExists(strParentFolder) Then '| '| '| 'If the parent folder of the base folder doesn't exist, '| '| '| 'the function is called recurrently to create it. '| '| '| Call createFolder(strParentFolder) '| '| '| End If '| '| '| '--------------------------------------------------------------------------------| '| '| '| '| '--------------------------------------------------------------------------------| '| '| On Error Resume Next '| '| '| Call .createFolder(folderPath) '| '| '| Set createFolder = .getFolder(folderPath) '| '| '| On Error GoTo 0 '| '| '| '--------------------------------------------------------------------------------| '| '| '| '| End If '| '| '-------- [If .DriveExists(strDriveName) Then] ------------------------------------------| '| '| End If '| '------------ [If .FolderExists(folderPath) Then] -----------------------------------------------| End With End Function '********************************************************************************************************** ' Name: getParentFolder ' Author: mielk | 2012-12-06 ' ' Comment: Function to return the path of the folder parental for the given path. ' ' Parameters: ' path The path for which the parent folder is to be returned. ' ' Returns: ' String The path of the parent folder for the specified path. ' If the given path has no parent folder (i.e. C:\), an empty string is returned. ' ' ' --- Changes log ----------------------------------------------------------------------------------------- ' 2012-12-06 mielk Function created. '********************************************************************************************************** Public Function getParentFolder(path As String) As String Const METHOD_NAME As String = "getParentFolder" '------------------------------------------------------------------------------------------------------ Static objFSO As Object '(Late binding that allows to use the function, even if 'Microsoft Scripting Runtime library is not loaded) '------------------------------------------------------------------------------------------------------ 'Create FileSystemObject instance if it hasn't been created yet. ------------------------------------| If objFSO Is Nothing Then '| Set objFSO = VBA.CreateObject("Scripting.FileSystemObject") '| End If '| '----------------------------------------------------------------------------------------------------| getParentFolder = objFSO.GetParentFolderName(path) End Function '********************************************************************************************************** ' Name: deleteFile ' Author: mielk | 2012-10-14 ' ' Comment: Function to delete the specified file from the file system. ' ' Parameters: ' filepath The path of a file to be deleted. ' ' Returns: ' Boolean True - if the given file has been deleted or the given file doesn't exist. ' False - if it was impossible to delete the given file (i.e. it is being used at ' this moment). ' ' ' --- Changes log ----------------------------------------------------------------------------------------- ' 2012-10-14 mielk Function created. '********************************************************************************************************** Public Function deleteFile(filepath As String) As Boolean Const METHOD_NAME As String = "deleteFile" Const ERR_NUM_FILE_NOT_FOUND As Long = 53 '------------------------------------------------------------------------------------------------------ Static objFSO As Object '(Late binding that allows to use the function, even if 'Microsoft Scripting Runtime library is not loaded) '------------------------------------------------------------------------------------------------------ 'Create FileSystemObject instance if it hasn't been created yet. ------------------------------------| If objFSO Is Nothing Then '| Set objFSO = VBA.CreateObject("Scripting.FileSystemObject") '| End If '| '----------------------------------------------------------------------------------------------------| 'Try to remove the given file. If it is not possible code moves to the DeleteFileException label. ---| On Error GoTo DeleteFileException '| Call objFSO.deleteFile(filepath) '| deleteFile = True '| '----------------------------------------------------------------------------------------------------| '========================================================================================================== ExitPoint: Exit Function '---------------------------------------------------------------------------------------------------------- DeleteFileException: If VBA.Err.number = ERR_NUM_FILE_NOT_FOUND Then 'File cannot be deleted because it doesn't exist. In this case True should be returned. deleteFile = True Else 'File cannot be deleted for any other reason. deleteFile = False End If GoTo ExitPoint End Function