codecaine

Excel VBA custom functions

May 5th, 2021 (edited)
724
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VBScript 23.29 KB | None | 0 0
  1. Option Explicit
  2. 'character set for non ascii non printable characters
  3. Private Const REGEX_ASCII_NON_PRINTABLE_PATTERN = "[\u0007-\u001F]"
  4.  
  5. 'character set for non-ascii characters
  6. Private Const REGEX_UNICODE_PATTERN = "[^\u0000-\u007F]"
  7.  
  8. Sub copyVisibleCells(rng As Range, destWorksheet As Worksheet)
  9.     'Select visible cells in a range and paste only the visible cells to another worksheet
  10.    rng.Select
  11.     Selection.SpecialCells(xlCellTypeVisible).Select
  12.  
  13.     'Copy Visible cells only in the range and paste in target sheet
  14.    Selection.Copy
  15.     destWorksheet.Select
  16.     destWorksheet.Paste
  17. End Sub
  18.  
  19. Sub copyVisibleCellsEnd(rng As Range, destWorksheet As Worksheet)
  20.     'Select visible cells in a range and paste only the visible cells to last row of worksheet
  21.    Dim rowIndex As Long
  22.    
  23.     If getVisibleRowCount(rng) = 1 Then
  24.         'exit sub if there is only a header and then select the destination worksheet
  25.        destWorksheet.Select
  26.         Exit Sub
  27.     End If
  28.    
  29.     Set rng = rng.Offset(1).Resize(rng.Rows.count - 1)
  30.  
  31.  
  32.     rng.SpecialCells(xlCellTypeVisible).Select
  33.     'Copy Visible cells only in the range and paste in target sheet
  34.    Selection.Copy
  35.     rowIndex = destWorksheet.Range("A1").CurrentRegion.Rows.count + 1
  36.     destWorksheet.Select
  37.     destWorksheet.Range("A" & rowIndex).Select
  38.     destWorksheet.Paste
  39. End Sub
  40.  
  41. Function getColumnCount(rng As Range) As Long
  42. 'return the number of columns from a range
  43.    getColumnCount = rng.Columns.count
  44. End Function
  45.  
  46. Function getRowCount(rng As Range) As Long
  47. 'returns the number of rows from a range
  48.    getRowCount = rng.Rows.count
  49. End Function
  50.  
  51. Function getVisibleColumnCount(rng As Range) As Long
  52. 'returns the number of visible columns from a range
  53.    Dim cellItem As Range
  54.     Dim count As Long
  55.     count = 0
  56.     For Each cellItem In rng.SpecialCells(xlCellTypeVisible).Columns
  57.         count = count + 1
  58.     Next cellItem
  59.     getVisibleColumnCount = count
  60. End Function
  61.  
  62. Function getVisibleRowCount(rng As Range) As Long
  63. 'return the number of visible rows from a range
  64.    Dim cellItem As Range
  65.     Dim count As Long
  66.     count = 0
  67.     For Each cellItem In rng.SpecialCells(xlCellTypeVisible).Rows
  68.         count = count + 1
  69.     Next cellItem
  70.     getVisibleRowCount = count
  71. End Function
  72.  
  73. Function isVisibleRowGreaterThan(rng As Range, rowCount) As Boolean
  74. 'return the number of visible rows from a range
  75.    Dim cellItem As Range
  76.     Dim count As Long
  77.     Dim isGreater As Boolean
  78.     count = 0
  79.     isGreater = False
  80.     For Each cellItem In rng.SpecialCells(xlCellTypeVisible).Rows
  81.         count = count + 1
  82.         If count > rowCount Then
  83.             isGreater = True
  84.             Exit For
  85.         End If
  86.     Next cellItem
  87.     isVisibleRowGreaterThan = isGreater
  88. End Function
  89.  
  90. Function fileExists(file As String) As Boolean
  91. 'check if a file exists returns true if yes and false if not
  92.    Dim fso As Object
  93.     Set fso = CreateObject("Scripting.FileSystemObject")
  94.     fileExists = fso.fileExists(file)
  95.     Set fso = Nothing
  96. End Function
  97.  
  98. Function folderExists(Path As String) As Boolean
  99. 'check if a folder exists or not returns true if exisit and false if not
  100.    Dim fso As Object
  101.     Set fso = CreateObject("Scripting.FileSystemObject")
  102.     folderExists = fso.folderExists(Path)
  103.     Set fso = Nothing
  104. End Function
  105.  
  106. Function moveFile(filePath As String, fileDest As String) As Boolean
  107. 'move file to new location of the file does not exists
  108.    Dim fso As Object
  109.     Set fso = CreateObject("Scripting.FileSystemObject")
  110.     If fileExists(filePath) Then
  111.         If Not fileExists(fileDest) Then
  112.             Call fso.moveFile(filePath, fileDest)
  113.         End If
  114.     End If
  115. End Function
  116.  Function getFileCount(psPath As String) As Long
  117. 'strive4peace
  118. 'uses Late Binding. Reference for Early Binding:
  119. '  Microsoft Scripting Runtime
  120.   'PARAMETER
  121.   '  psPath is folder to get the number of files for
  122.   '     for example, c:\myPath
  123.   ' Return: Long
  124.   '    -1 = path not valid
  125.   '     0 = no files found, but path is valid
  126.   '    99 = number of files where 99 is some number
  127.  
  128.    'inialize return value
  129.   getFileCount = -1
  130.    'skip errors
  131.   On Error Resume Next
  132.    'count files in folder of FileSystemObject for path
  133.   With CreateObject("Scripting.FileSystemObject")
  134.       getFileCount = .GetFolder(psPath).Files.count
  135.    End With
  136. End Function
  137.  
  138. Function getFileNamesFromPath(Path As String, Optional ext As String = "", Optional excludePrefix As String = "") As Collection
  139. 'returns filenames from a folder path
  140. 'if ext is not empty then filter file names by file extension. Example of ext parameter file extension strings docx, exe
  141. 'if excludePrefix is not empty exclude all files from folder that begins with the prefix string
  142.    Dim col As New Collection
  143.     Dim filename As String
  144.    
  145.     'remove trailing spaces from path
  146.    Path = Trim(Path)
  147.    
  148.     'exit function if the path does not exists
  149.    If Path = "" Then
  150.         Set getFileNamesFromPath = col
  151.         Exit Function
  152.     End If
  153.    
  154.     'add trailing space to path if the path if there is no trialing space
  155.    If Not regexTest(Path, "\\$") Then
  156.          Path = Path & "\"
  157.     End If
  158.  
  159.     'filter not filter by file extension
  160.    If ext <> "" Then
  161.         filename = Dir(Path & "*." & ext, vbNormal & vbHidden)
  162.     Else
  163.         filename = Dir(Path, vbNormal & vbHidden)
  164.     End If
  165.    
  166.     'add files names to collection and exclude files with a certain prefix if excludePrefix is not a empty string
  167.    Do While filename <> ""
  168.         If excludePrefix <> "" Then
  169.             If InStr(1, filename, excludePrefix) = 0 Then
  170.                 col.Add filename
  171.             End If
  172.         Else
  173.             col.Add filename
  174.         End If
  175.         filename = Dir
  176.     Loop
  177.    
  178.     Set getFileNamesFromPath = col
  179. End Function
  180.  
  181. Function deleteFolder(folderPath As String) As Boolean
  182. 'delete a folder from folder path
  183. 'this function deletes empty or non empty folder
  184. 'the function will failed if there is a permission access issue else returns true
  185. 'if the folder does not exists true is returned
  186.    Dim fso As Object
  187.     Dim tempPath As String
  188.     tempPath = Trim(folderPath)
  189.     If tempPath <> "" Then
  190.         If Right(tempPath, 1) = "\" Then
  191.             tempPath = Left(tempPath, Len(tempPath) - 1)
  192.         End If
  193.     End If
  194.  
  195.     On Error GoTo errHandler:
  196.     Set fso = CreateObject("Scripting.FileSystemObject")
  197.     If fso.folderExists(tempPath) Then
  198.         Call fso.deleteFolder(tempPath)
  199.     End If
  200.    
  201.     deleteFolder = True
  202. exitSuccess:
  203.     Exit Function
  204. errHandler:
  205.     Debug.Print Err.number, Err.Description
  206.     GoTo exitSuccess
  207. End Function
  208.  
  209. Function getFolderCount(psPath As String) As Long
  210. 'strive4peace
  211. 'uses Late Binding. Reference for Early Binding:
  212. '  Microsoft Scripting Runtime
  213.   'PARAMETER
  214.   '  psPath is path to get the number of folders for
  215.   '     for example, c:\myPath
  216.   ' Return: Long
  217.   '  -1 = path not valid
  218.   '   0 = no folders found, but path is valid
  219.   '  99 = number of folders where 99 is some number
  220.  
  221.    'inialize return value
  222.   getFolderCount = -1
  223.    'skip errors
  224.   On Error Resume Next
  225.    'count SubFolders in FileSystemObject for psPath
  226.   With CreateObject("Scripting.FileSystemObject")
  227.       getFolderCount = .GetFolder(psPath).SubFolders.count
  228.    End With
  229. End Function
  230.  
  231. Function columnNumToColumnLetter(colNum As Long) As String
  232. 'returns an excel column letter from the number number
  233. 'if the column letter cannot be determine returns vbnullstring
  234.    Dim regex As Object
  235.     Dim Matches As Object
  236.     Dim addr As String
  237.     Set regex = CreateObject("VBScript.RegExp")
  238.     regex.pattern = "[A-Z]+"
  239.     addr = Cells(1, colNum).Address(False, False)
  240.     If regex.test(addr) Then
  241.         Set Matches = regex.Execute(addr)
  242.         columnNumToColumnLetter = Matches(0)
  243.     Else
  244.         columnNumToColumnLetter = ""
  245.     End If
  246.     Set regex = Nothing
  247.     Set Matches = Nothing
  248. End Function
  249.  
  250. Sub deleteRowIfCellBlank(rng As Range)
  251. 'delete the entire row if any cells are blank
  252.    On Error Resume Next
  253.  
  254.     rng.Cells.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
  255. End Sub
  256.  
  257. Function getColumnIndex(rng As Range, heading As String, Optional ColumnLetter As Boolean = False) As Variant
  258. 'returns heading column letter or number if the header is found else returns 0
  259. 'if ColumnLetter is true a letter is return if the column is found else 0
  260.    Dim title As Range
  261.     Dim HEADER As Range
  262.     Set title = rng.Rows(1)
  263.     For Each HEADER In title.Cells
  264.         If StrComp(HEADER.Value, heading, vbTextCompare) = 0 Then
  265.             If ColumnLetter = False Then
  266.                 getColumnIndex = HEADER.Column
  267.             Else
  268.                 getColumnIndex = columnNumToColumnLetter(HEADER.Column)
  269.             End If
  270.             Exit Function
  271.         End If
  272.    
  273.     Next HEADER
  274.     getColumnIndex = 0
  275.     Set title = Nothing
  276. End Function
  277.  
  278. Function rangeToArray(rng As Range) As Variant
  279. 'returns a range of values as an array
  280.  
  281.     ' Declare dynamic array
  282.    Dim tempArray As Variant
  283.  
  284.     ' tempArray values into array from first row
  285.    rangeToArray = rng.Value
  286. End Function
  287.  
  288. Sub arrayToRange(arr As Variant, rng As Range)
  289. 'copies array values to a range
  290. 'example Range("A1:C1] = Array[1,2,3]
  291.    rng.Value = arr
  292. End Sub
  293.  
  294. Function worksheetExists(sheetName As String) As Boolean
  295. 'checks active workbook if a worksheet exists
  296.    Dim ws As Worksheet
  297.       For Each ws In Application.ActiveWorkbook.Worksheets
  298.         If sheetName = ws.Name Then
  299.           worksheetExists = True
  300.           Exit For
  301.         End If
  302.       Next ws
  303. End Function
  304.  
  305. Function worksheetDelete(sheetName As String) As Boolean
  306. 'delete worksheet if the workseet exists in the active workbook by worksheet name
  307.    If worksheetExists(sheetName) Then
  308.         ActiveWorkbook.Worksheets(sheetName).Delete
  309.     End If
  310.     worksheetDelete = True
  311. End Function
  312.  
  313. Function worksheetCreate(sheetName As String, Optional sheetIndex As Integer = 0) As Worksheet
  314. ' create a worksheet with provided sheetname in active workbook
  315.    Dim objSheet As Object
  316.     On Error GoTo errHandler
  317.     If sheetIndex = 0 Then
  318.         sheetIndex = Sheets.count
  319.     End If
  320.     Set objSheet = Sheets.Add(After:=Sheets(sheetIndex))
  321.     objSheet.Name = sheetName
  322.     Set worksheetCreate = objSheet
  323.     Exit Function
  324. errHandler:
  325.     Debug.Print Err.number, Err.Description
  326. End Function
  327.  
  328. Function worksheetCopy(wsName As String, Optional wbPath = "", Optional newWsName = "") As Boolean
  329. 'copies a worksheet from within the same workbook or from an external workbook
  330. 'if newWsName is not an empty string the copied worksheet is renamed to the newWsName
  331.    Dim tempActiveWorkbook As Workbook, wbExternal As Workbook
  332.     On Error GoTo errHandler
  333.     Set tempActiveWorkbook = ActiveWorkbook
  334.     'delete sales force worksheet if it already exists
  335.    If wbPath <> "" Then
  336.         Set wbExternal = Workbooks.Open(filename:=wbPath)
  337.         wbExternal.Sheets(wsName).Copy After:=Workbooks(tempActiveWorkbook.Name).Sheets(tempActiveWorkbook.Sheets.count)
  338.         wbExternal.Close SaveChanges:=False
  339.     Else
  340.         tempActiveWorkbook.Sheets(wsName).Copy After:=Workbooks(tempActiveWorkbook.Name).Sheets(tempActiveWorkbook.Sheets.count)
  341.     End If
  342.    
  343.     If newWsName <> "" Then
  344.         tempActiveWorkbook.ActiveSheet.Name = newWsName
  345.     End If
  346.    
  347.     worksheetCopy = True
  348. exitSuccess:
  349.     Set tempActiveWorkbook = Nothing
  350.     Set wbExternal = Nothing
  351.     Exit Function
  352. errHandler:
  353.     MsgBox Err.Description
  354.     Resume exitSuccess
  355. End Function
  356.  
  357. Sub worksheetUnhideAllRows(Optional ws As Worksheet)
  358. 'unhide all rows in a worksheet
  359. 'if no worksheet is provided then the active worksheet is used
  360. If ws Is Nothing Then
  361.     Set ws = ActiveSheet
  362. End If
  363.     ws.Rows.EntireRow.Hidden = False
  364. End Sub
  365.  
  366. Sub worksheetUnhideAllColumns(Optional ws As Worksheet)
  367. 'unhide all columns in a worksheet
  368. 'if no worksheet is provided then the active worksheet is used
  369. If ws Is Nothing Then
  370.     Set ws = ActiveSheet
  371. End If
  372.     ws.Rows.EntireColumn.Hidden = False
  373. End Sub
  374.  
  375. Sub worksheetUnhideAllRowsAndColumns(Optional ws As Worksheet)
  376. 'unhide all rows and columns in a worksheet
  377. 'if no worksheet is provided then the active worksheet is used
  378. If ws Is Nothing Then
  379.     Set ws = ActiveSheet
  380. End If
  381.     Call worksheetUnhideAllRows(ws)
  382.     Call worksheetUnhideAllColumns(ws)
  383. End Sub
  384.  
  385. Function worksheetIsFilterMode(Optional ws As Worksheet) As Boolean
  386. 'returns true if a worksheet has a filter applied else false
  387. 'if no worksheet is provided teh active worksheet is used
  388.    If ws Is Nothing Then
  389.         Set ws = ActiveSheet
  390.     End If
  391.     worksheetIsFilterMode = ws.FilterMode
  392. End Function
  393.  
  394. Sub worksheetClearFilter(Optional ws As Worksheet)
  395. 'unfilter a worksheet if it worksheet is filtered
  396. 'if no worksheet is provided teh active worksheet is used
  397. If ws Is Nothing Then
  398.         Set ws = ActiveSheet
  399.     End If
  400.     If worksheetIsFilterMode(ws) Then
  401.         ws.ShowAllData
  402.     End If
  403. End Sub
  404.  
  405. Sub worksheetShowAllData(Optional ws As Worksheet)
  406. 'unhides all rows, columns and remove filters from a worksheet
  407. 'if no worksheet is provided the active worksheet is used
  408.    If worksheetIsFilterMode(ws) Then
  409.         ws.ShowAllData
  410.     End If
  411.     Call worksheetUnhideAllRowsAndColumns
  412. End Sub
  413.  
  414. '''''''''''''''''''''''''''''''''''''''''''''''''''''
  415. '             String Functions Section              '
  416. '''''''''''''''''''''''''''''''''''''''''''''''''''''
  417.  
  418. 'ASCII char URL https://www.ibm.com/support/knowledgecenter/en/ssw_aix_72/com.ibm.aix.networkcomm/conversion_table.htm
  419.  
  420.  
  421. Public Function regexTest(strData As String, pattern As String, Optional isGlobal As Boolean = True, Optional isIgnoreCase As Boolean = True, Optional isMultiLine As Boolean = True) As Boolean
  422. 'returns true if a pattern match else false
  423.  
  424. Dim objRegex As Object
  425.  
  426. On Error GoTo errHandler
  427.  
  428. Set objRegex = CreateObject("vbScript.regExp")
  429. With objRegex
  430.     .Global = isGlobal
  431.     .ignoreCase = isIgnoreCase
  432.     .MultiLine = isMultiLine
  433.     .pattern = pattern
  434.     'if the pattern is a match then replace the text else return the orginal string
  435.    If .test(strData) Then
  436.         regexTest = True
  437.     Else
  438.         regexTest = False
  439.     End If
  440. End With
  441. exitSuccess:
  442.     Set objRegex = Nothing
  443.     Exit Function
  444. errHandler:
  445.     regexTest = False
  446.     Debug.Print Err.Description
  447.     Resume exitSuccess
  448. End Function
  449.  
  450. Function regexMatches(data As String, pattern As String, Optional ignoreCase As Boolean = True, Optional globalMatches As Boolean = True) As Collection
  451. 'return a collection found from a pattern using regular expressions
  452.  
  453.     Dim regex As Object, theMatches As Object, match As Object
  454.     Dim col As New Collection
  455.     Set regex = CreateObject("vbScript.regExp")
  456.      
  457.     regex.pattern = pattern
  458.     regex.Global = globalMatches
  459.     regex.ignoreCase = ignoreCase
  460.      
  461.     Set theMatches = regex.Execute(data)
  462.      
  463.     For Each match In theMatches
  464.       col.Add match.Value
  465.     Next
  466.    
  467.     Set regexMatches = col
  468. End Function
  469.  
  470. Function regexFirstMatch(data As String, pattern As String, Optional ignoreCase As Boolean = True, Optional globalMatches As Boolean = True) As String
  471. 'returns the first match from a regular expression pattern
  472.  
  473.     Dim regex As Object, theMatches As Object, match As Object
  474.     Set regex = CreateObject("vbScript.regExp")
  475.      
  476.     regex.pattern = pattern
  477.     regex.Global = globalMatches
  478.     regex.ignoreCase = ignoreCase
  479.      
  480.     Set theMatches = regex.Execute(data)
  481.      
  482.     For Each match In theMatches
  483.       regexFirstMatch = match.Value
  484.       Exit For
  485.     Next
  486.  
  487. End Function
  488.  
  489. Function regexReplace(strData As String, pattern As String, Optional replace_with_str = vbNullString, Optional isGlobal As Boolean = True, Optional isIgnoreCase As Boolean = True, Optional isMultiLine As Boolean = True) As String
  490. 'returns string replacing data using a regex pattern
  491.  
  492.     Dim objRegex As Object
  493.  
  494. On Error GoTo errHandler
  495.     Set objRegex = CreateObject("vbScript.regExp")
  496.     With objRegex
  497.         .Global = isGlobal
  498.         .ignoreCase = isIgnoreCase
  499.         .MultiLine = isMultiLine
  500.         .pattern = pattern
  501.         'if the pattern is a match then replace the text else return the orginal string
  502.        If .test(strData) Then
  503.             regexReplace = .Replace(strData, replace_with_str)
  504.         Else
  505.             regexReplace = strData
  506.         End If
  507.     End With
  508. exitSuccess:
  509.     Set objRegex = Nothing
  510.     Exit Function
  511. errHandler:
  512.     regexReplace = strData
  513.     Debug.Print Err.Description
  514.     Resume exitSuccess
  515. End Function
  516.  
  517. Function regexPatternCount(strData As String, pattern As String, Optional isGlobal As Boolean = True, Optional isIgnoreCase As Boolean = True, Optional isMultiLine As Boolean = True) As Long
  518. 'returns the number of matters matches in a string using regex
  519. '-1 will return if there was an error
  520.  
  521.     Dim objRegex As Object
  522.     Dim Matches As Object
  523.  
  524. On Error GoTo errHandler
  525.     Set objRegex = CreateObject("vbScript.regExp")
  526.     objRegex.pattern = pattern
  527.     objRegex.Global = isGlobal
  528.     objRegex.ignoreCase = isIgnoreCase
  529.     objRegex.MultiLine = isMultiLine
  530.     'Retrieve all matches
  531.    Set Matches = objRegex.Execute(strData)
  532.     'Return the pattern matches count
  533.    regexPatternCount = Matches.count
  534. exitSuccess:
  535.     Set Matches = Nothing
  536.     Set objRegex = Nothing
  537.     Exit Function
  538. errHandler:
  539.     regexPatternCount = -1
  540.     Resume exitSuccess
  541. End Function
  542.  
  543. Function regexRemoveConcatDupChars(data As String) As String
  544. 'remove duplicates characters when concatenated together
  545.    regexRemoveConcatDupChars = regexReplace(data, "(.)\1+", "$1")
  546. End Function
  547.  
  548. Function regexContainsConcatDupChars(data As String) As Boolean
  549. 'returns true if there are concatenated characters of the same type in as string provided
  550.    regexContainsConcatDupChars = regexPatternCount(data, "(.)\1+")
  551. End Function
  552.  
  553. Function regexContainsNonAscii(data As String) As Boolean
  554. 'returns true if a string contains unicode characters else false
  555.    If regexPatternCount(data, REGEX_UNICODE_PATTERN) > 0 Then
  556.         regexContainsNonAscii = True
  557.     Else
  558.         regexContainsNonAscii = False
  559.     End If
  560. End Function
  561.  
  562. Function regexLeftTrim(data As String) As String
  563. 'returns a string removing spaces and tab characters from the beginning of a string only
  564.    regexLeftTrim = regexReplace(data, "^[\s\t]+")
  565. End Function
  566.  
  567. Function regexRightTrim(data As String) As String
  568. 'returns a string removing spaces and tab characters from the beginning and end of a string
  569.    regexRightTrim = regexReplace(data, "[\s\t]+$")
  570. End Function
  571.  
  572. Function regexTrim(data As String) As String
  573. 'returns a string removing spaces and tab characters from the beginning and end of a string
  574.    data = regexLeftTrim(data)
  575.     data = regexRightTrim(data)
  576.     regexTrim = data
  577. End Function
  578.  
  579. Function setFirstLetterCapitalized(data As String) As String
  580. 'returns a string with first letter capitialize
  581.    If Len(data) = 0 Then
  582.         setFirstLetterCapitalized = ""
  583.     Else
  584.         setFirstLetterCapitalized = UCase(Mid(data, 1, 1)) & Mid(data, 2, Len(data))
  585.     End If
  586. End Function
  587.  
  588. Function setProperCase(data As String) As String
  589. 'returns a string with all words starting with a capital letter and the rest lowercase
  590.    setProperCase = StrConv(data, vbProperCase)
  591. End Function
  592.  
  593. Function sqlStrFormat(data As String) As String
  594. 'returns a string replacing single quotes with double single quotes
  595.    Const SINGLE_QUOTE_CHAR = "'"
  596.     sqlStrFormat = Replace(data, SINGLE_QUOTE_CHAR, SINGLE_QUOTE_CHAR & SINGLE_QUOTE_CHAR)
  597. End Function
  598.  
  599. Private Sub displayError(Optional toImmediateWindow As Boolean = True)
  600. 'display error code number and description in the immediate window by default
  601. 'if toImmediateWindow is false then the error is displayed in a messagebox
  602. 'this subroutine is used for ON ERROR GoTo statements error handler section
  603.    If toImmediateWindow Then
  604.         Debug.Print Err.number, Err.Description
  605.     Else
  606.         MsgBox Err.number & " " & Err.Description, vbCritical
  607.     End If
  608. End Sub
  609.  
  610. Function createDictionary(Optional ignoreCase As Boolean = False) As Object
  611. 'returns a dictionary object
  612. 'if ignore case is true the dictionary keys will not be case sensitive. The default is case sensitive
  613.    Dim dict As Object
  614.    
  615.     Set dict = CreateObject("Scripting.Dictionary")
  616.    
  617.     If ignoreCase Then
  618.         dict.comparemode = vbTextCompare
  619.     End If
  620.    
  621.     Set createDictionary = dict
  622. End Function
  623.  
  624. Function isValueInRange(rng As Range, search As String, Optional lookIn As XlFindLookIn = XlFindLookIn.xlFormulas, Optional lookAt As XlLookAt = XlLookAt.xlWhole, Optional matchCase As Boolean = False) As String
  625. 'returns string address of the cell where the value if found in the range
  626. 'if the value is not found than an empty string is returned
  627.  
  628.     Dim cell As Range
  629.    
  630.     Set cell = rng.Find(What:=search, lookIn:=lookIn, lookAt:=lookAt, matchCase:=matchCase)
  631.    
  632.     If cell Is Nothing Then
  633.         isValueInRange = ""
  634.     Else
  635.         isValueInRange = cell.Address
  636.     End If
  637.  
  638. End Function
  639.  
  640. Function countNumberOfNonBlankCells(rng As Range) As Long
  641. 'returns the count of cells that are not empty
  642.    countNumberOfNonBlankCells = Application.WorksheetFunction.CountA(rng)
  643. End Function
  644.  
  645. Sub quickSort(vArray As Variant, inLow As Long, inHi As Long)
  646. 'sort an array in ascending order
  647. 'example quickSort(arr, LBound(arr), UBound(arr))
  648.  Dim pivot   As Variant
  649.   Dim tmpSwap As Variant
  650.   Dim tmpLow  As Long
  651.   Dim tmpHi   As Long
  652.  
  653.   tmpLow = inLow
  654.   tmpHi = inHi
  655.  
  656.   pivot = vArray((inLow + inHi) \ 2)
  657.  
  658.   While (tmpLow <= tmpHi)
  659.  
  660.      While (vArray(tmpLow) < pivot And tmpLow < inHi)
  661.         tmpLow = tmpLow + 1
  662.      Wend
  663.  
  664.      While (pivot < vArray(tmpHi) And tmpHi > inLow)
  665.         tmpHi = tmpHi - 1
  666.      Wend
  667.  
  668.      If (tmpLow <= tmpHi) Then
  669.         tmpSwap = vArray(tmpLow)
  670.         vArray(tmpLow) = vArray(tmpHi)
  671.         vArray(tmpHi) = tmpSwap
  672.         tmpLow = tmpLow + 1
  673.         tmpHi = tmpHi - 1
  674.      End If
  675.  
  676.   Wend
  677.  
  678.   If (inLow < tmpHi) Then quickSort vArray, inLow, tmpHi
  679.   If (tmpLow < inHi) Then quickSort vArray, tmpLow, inHi
  680.  
  681. End Sub
  682.  
  683. Function binarySearch(lookupArray As Variant, lookupValue As Variant) As Long
  684. 'binary search lookup for arrays
  685. 'the array must be sorted when using this function
  686. '-1 is return if not found else the index of where the item is found
  687.  
  688.     Dim lngLower As Long
  689.     Dim lngMiddle As Long
  690.     Dim lngUpper As Long
  691.  
  692.     lngLower = LBound(lookupArray)
  693.     lngUpper = UBound(lookupArray)
  694.  
  695.     Do While lngLower < lngUpper
  696.        
  697.         lngMiddle = (lngLower + lngUpper) \ 2
  698.  
  699.         If lookupValue > lookupArray(lngMiddle) Then
  700.             lngLower = lngMiddle + 1
  701.         Else
  702.             lngUpper = lngMiddle
  703.         End If
  704.        
  705.     Loop
  706.    
  707.     If lookupArray(lngLower) = lookupValue Then
  708.         binarySearch = lngLower
  709.     Else
  710.         binarySearch = -1    'search does not find a match
  711.    End If
  712. End Function
  713.  
  714. Function collectionToArray(col As Collection) As Variant
  715. 'returns an array from a collection object
  716.    Dim result  As Variant
  717.     Dim cnt     As Long
  718.    
  719.     ReDim result(col.count - 1)
  720.  
  721.     For cnt = 0 To col.count - 1
  722.         result(cnt) = col(cnt + 1)
  723.     Next cnt
  724.  
  725.     collectionToArray = result
  726. End Function
  727.  
  728.  
  729.  
  730.  
Add Comment
Please, Sign In to add comment