Advertisement
ChrisProsser

gen_vba_library

Jul 24th, 2013
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Option Explicit
  2.  
  3. ' NOTE: replace gen.ErrHandler calls with below where the ErrHandler proc will not be available:
  4. '    Debug.Print "Error in ", cProcName, vbCrLf, "Err no: ", Err.Number, _
  5.                 vbCrLf, "Err Description: ", Err.Description
  6.  
  7. ' Global constants / variables
  8. Public Const gcSupportDetails = "<support_email_add_here>"
  9. Public Const gcErrMsgOn As Boolean = True
  10. Public Const gcMsgLimit As Integer = 5
  11. Public gvErrCount As Integer
  12. Public gvErrBefore As Integer
  13. Public gvErrString As String
  14. Public gvErrNotes As String
  15.  
  16. Sub InitialiseGlobalVars()
  17. On Error GoTo InitialiseGlobalVars_err
  18.  
  19.     ' Local constants / variables
  20.    Const cProcName = "InitialiseGlobalVars"
  21.  
  22.     'Initialise Globals
  23.    gvErrCount = 0
  24.     gvErrBefore = 0
  25.     gvErrString = Empty
  26.     gvErrNotes = Empty
  27.    
  28. InitialiseGlobalVars_exit:
  29.     Exit Sub
  30.    
  31. InitialiseGlobalVars_err:
  32.     Call Gen.ErrHandler(cProcName, Err.Number, Err.Description)
  33.     Resume Next
  34.  
  35. End Sub
  36.  
  37. Function NextAvailableRow()
  38. On Error GoTo NextAvailableRow_err
  39. ' Goes from currently active cell and finds the next available row
  40.  
  41.     ' Local constants / variables
  42.    Const cProcName = "NextAvailableRow"
  43.  
  44.     If ActiveCell.Value = "" Then
  45.         NextAvailableRow = ActiveCell.row
  46.     Else
  47.         NextAvailableRow = ActiveCell.End(xlDown).row + 1
  48.     End If
  49.    
  50. NextAvailableRow_exit:
  51.     Exit Function
  52.    
  53. NextAvailableRow_err:
  54.     Call Gen.ErrHandler(cProcName, Err.Number, Err.Description)
  55.     Resume Next
  56.  
  57. End Function
  58.  
  59. Function NextAvailableCol()
  60. On Error GoTo NextAvailableCol_err
  61. ' Goes from currently active cell and finds the next available row
  62.  
  63.     ' Local constants / variables
  64.    Const cProcName = "NextAvailableCol"
  65.  
  66.     If ActiveCell.Value = "" Then
  67.         NextAvailableCol = ColNoToLetter(ActiveCell.Column)
  68.     Else
  69.         NextAvailableCol = ColNoToLetter(ActiveCell.End(xlToRight).Column + 1)
  70.     End If
  71.    
  72. NextAvailableCol_exit:
  73.     Exit Function
  74.    
  75. NextAvailableCol_err:
  76.     Call Gen.ErrHandler(cProcName, Err.Number, Err.Description)
  77.     Resume Next
  78.  
  79. End Function
  80.  
  81. Function LastRow(p_sheet As String, p_cell_address As String)
  82. On Error GoTo LastRow_err
  83. ' Looks from address sent in as parameter to find the last row populated before a break
  84.  
  85.     ' Local constants / variables
  86.    Const cProcName = "LastRow"
  87.    
  88.     LastRow = Sheets(p_sheet).Range(p_cell_address).End(xlDown).row
  89.    
  90. LastRow_exit:
  91.     Exit Function
  92.    
  93. LastRow_err:
  94.     Call Gen.ErrHandler(cProcName, Err.Number, Err.Description)
  95.     Resume Next
  96.  
  97. End Function
  98.  
  99. Function LastCol(p_sheet As String, p_cell_address As String)
  100. On Error GoTo LastCol_err
  101. ' Looks from address sent in as parameter to find the last column populated before a break, returns a letter
  102.  
  103.     ' Local constants / variables
  104.    Const cProcName = "LastCol"
  105.    
  106.     LastCol = Gen.ColNoToLetter(Sheets(p_sheet).Range(p_cell_address).End(xlToRight).Column)
  107.    
  108. LastCol_exit:
  109.     Exit Function
  110.    
  111. LastCol_err:
  112.     Call Gen.ErrHandler(cProcName, Err.Number, Err.Description)
  113.     Resume Next
  114.  
  115. End Function
  116.  
  117. Function ColNoToLetter(pColNo As Integer)
  118. On Error GoTo ColNoToLetter_err
  119. ' Goes from currently active cell and finds the next available row
  120.  
  121.     ' Local constants / variables
  122.    Const cProcName = "ColNoToLetter"
  123.     Dim vNumberOne As Integer
  124.     Dim vNumberTwo As Integer
  125.     Dim vLetterOne As String
  126.     Dim vLetterTwo As String
  127.    
  128.     vNumberOne = 0
  129.     vNumberTwo = 0
  130.     vLetterOne = Empty
  131.     vLetterTwo = Empty
  132.    
  133.     vNumberOne = Int((pColNo - 1) / 26)
  134.     vNumberTwo = pColNo - (vNumberOne * 26)
  135.     vLetterTwo = Chr(vNumberTwo + 64)
  136.    
  137.     If vNumberOne >= 1 Then
  138.         vLetterOne = Chr(vNumberOne + 64)
  139.     End If
  140.    
  141.     ColNoToLetter = vLetterOne & vLetterTwo
  142.    
  143. ColNoToLetter_exit:
  144.     Exit Function
  145.    
  146. ColNoToLetter_err:
  147.     Call Gen.ErrHandler(cProcName, Err.Number, Err.Description)
  148.     Resume Next
  149.  
  150. End Function
  151.  
  152. Function SheetExists(pSheetName As String, _
  153.                                        pCreateIfNotExists As Boolean, _
  154.                                        pGoToSheet As Boolean, _
  155.                                        pAcceptPartialMatch As Boolean) As Boolean
  156. On Error GoTo SheetExists_err
  157.  
  158.     ' Local constants / variables
  159.    Const cProcName = "SheetExists"
  160.     Dim vSheet As Worksheet
  161.     Dim vSheetNo As Integer
  162.     Dim vCurrSheetName As String
  163.     Dim vSearchFor As String
  164.    
  165.     vSheetNo = 0
  166.     vCurrSheetName = Empty
  167.     vSearchFor = Empty
  168.    
  169.     If pAcceptPartialMatch = True Then
  170.         vSearchFor = "*" & pSheetName & "*"
  171.     Else
  172.         vSearchFor = pSheetName
  173.     End If
  174.    
  175.     For Each vSheet In Worksheets
  176.         vSheetNo = vSheetNo + 1
  177.         vCurrSheetName = vSheet.Name
  178.         If vCurrSheetName Like vSearchFor Then
  179.             SheetExists = True
  180.             Exit For
  181.         Else
  182.             SheetExists = False
  183.         End If
  184.     Next
  185.    
  186.     If pCreateIfNotExists = True Then
  187.         If SheetExists = False Then
  188.             Sheets.add().Name = pSheetName
  189.             vCurrSheetName = pSheetName
  190.         End If
  191.     End If
  192.    
  193.     If pGoToSheet = True Then
  194.        
  195.         ' Use vCurrSheetName as if accepting partial matches pSheetname may not exist
  196.        Sheets(vCurrSheetName).Select
  197.         Range("A1").Select
  198.         ActiveWindow.DisplayGridlines = False
  199.     End If
  200.    
  201. SheetExists_exit:
  202.     Exit Function
  203.    
  204. SheetExists_err:
  205.     'If Err.Number = 9 Then
  206.    '    Debug.Print "Err No:" & vbTab & Err.Number & ", " & vbTab & "Err Desc:" & vbTab & Err.Description
  207.    '    Resume Next
  208.    'Else
  209.        Call Gen.ErrHandler(cProcName, Err.Number, Err.Description)
  210.         Resume Next
  211.     'End If
  212.  
  213. End Function
  214.  
  215. Sub ExtendRowHeight(Optional pAutoSize As Boolean = True, _
  216.                                         Optional pAlignToTop As Boolean = True, _
  217.                                         Optional pAddToColHeight As Single = 10, _
  218.                                         Optional pStartFromRow As Integer = 2)
  219. On Error GoTo ExtendRowHeight_err
  220.  
  221.     ' Local constants / variables
  222.    Const cProcName = "ExtendRowHeight"
  223.     Dim vEnd As Integer
  224.     Dim vRow As Integer
  225.  
  226.     ActiveSheet.Range("A" & pStartFromRow).Select
  227.     vEnd = ActiveCell.CurrentRegion.Rows.Count
  228.     vRow = 0
  229.    
  230.     Rows(pStartFromRow & ":" & vEnd).Select
  231.    
  232.     ' Set based row height to autosize if required
  233.    If pAutoSize = True Then
  234.         With Selection
  235.             .ShrinkToFit = False
  236.         End With
  237.     End If
  238.    
  239.     ' Set vertical alignment if required
  240.    If pAlignToTop = True Then
  241.         With Selection
  242.             If ActiveCell.RowHeight > 15 Then
  243.                 .VerticalAlignment = xlTop
  244.             Else
  245.                 .VerticalAlignment = xlCenter
  246.             End If
  247.         End With
  248.     End If
  249.    
  250.     ActiveSheet.Range("A" & pStartFromRow).Select
  251.    
  252.     ' Loop through to ad x to the row height (if <> 0
  253.    If pAddToColHeight <> 0 Then
  254.         For vRow = pStartFromRow To vEnd
  255.             ActiveCell.RowHeight = ActiveCell.RowHeight + pAddToColHeight
  256.             ActiveCell.Offset(1, 0).Select
  257.         Next vRow
  258.     Else
  259.         Debug.Print "Parameter passed in to add 0 to row height so no need to loop through"
  260.     End If
  261.    
  262.     ActiveSheet.Range("A" & pStartFromRow).Select
  263.    
  264. ExtendRowHeight_exit:
  265.     Exit Sub
  266.    
  267. ExtendRowHeight_err:
  268.     Call Gen.ErrHandler(cProcName, Err.Number, Err.Description)
  269.     Resume Next
  270.  
  271. End Sub
  272.  
  273.  
  274. Sub ErrHandler(pErrSource, pErrNo, pErrDesc)
  275. On Error GoTo ErrHandler_err
  276.  
  277.     ' Local constants / variables
  278.    Const cProcName = "ErrHandler"
  279.  
  280.     ' Set description on user defined errors (or revert to pErrDesc for others)
  281.    If pErrNo = 40001 Then
  282.         gvErrNotes = "A user defined error occurred processing the " & gcBatchScript & " procedure."
  283.     ElseIf pErrNo = 40002 Then
  284.         gvErrNotes = "A user defined error occurred during the " & pErrSource & " procedure."
  285.     ElseIf pErrNo = 50000 Then
  286.         gvErrNotes = "User defined error raised to test error handling functionality."
  287.     Else
  288.         gvErrNotes = pErrDesc
  289.     End If
  290.    
  291.     ' Update error count and logging details
  292.    gvErrCount = gvErrCount + 1
  293.     gvErrString = gvErrString & Chr(10) & Chr(10) & "ErrCount: " & gvErrCount & ", " & _
  294.                           "Error occurred in " & pErrSource & " procedure, " & Chr(10) & _
  295.                           "Err_No: " & pErrNo & ", " & _
  296.                           "Err_Desc: " & gvErrNotes
  297.    
  298.     ' Uncomment to test error handling procedure
  299.    '--Error (50001)
  300.    
  301.     If gcErrMsgOn And gvErrCount <= gcMsgLimit Then
  302.         ' Raise message for user
  303.        MsgBox ("An error occurred in the " & pErrSource & " procedure / function, details:" & vbCrLf & _
  304.         "____________________________________________________________________________" & _
  305.         vbCrLf & vbCrLf & _
  306.         "Error Number:" & vbTab & pErrNo & vbCrLf & _
  307.         "Description:" & vbTab & gvErrNotes & vbCrLf & _
  308.         "____________________________________________________________________________" & _
  309.         vbCrLf & vbCrLf & _
  310.         "If you are still experiencing problems please report the issue to: " & gcSupportDetails & _
  311.         "." & vbTab & vbCrLf & vbCrLf)
  312.        
  313.         ' **** alternative msg for imports: ****
  314.        'vbCrLf & vbCrLf & _
  315.         '"Please note the following points:" & vbCrLf & vbCrLf & _
  316.         '">  You must have access to the " & gcRawDataPath & " directory to run this spreadsheet." & vbCrLf & _
  317.         '">  You can confirm this by going to the Start Menu, Run and entering " & gcRawDataPath & vbCrLf & _
  318.         '">  This spreadsheet should be contained within the same directory" & vbCrLf & _
  319.         '"    (shortcuts are okay as long as they link to this directory as the target address)" & vbCrLf & vbCrLf & _
  320.         '"If you are still experiencing problems please report the issue to: " & gcSupportDetails & "." & vbTab & vbCrLf & _
  321.         '"Details of this error should be recorded in the Log sheet." & vbCrLf)
  322.    End If
  323.  
  324. ErrHandler_exit:
  325.     Exit Sub
  326.  
  327. ErrHandler_err:
  328.     Debug.Print "*** Error in error handling procedure. Oh dear, something has gone very wrong! ***"
  329.     gvErrCount = gvErrCount + 1
  330.     gvErrString = gvErrString & Chr(10) & Chr(10) & "ErrCount: " & gvErrCount & ", " & _
  331.                           "Error occurred in " & cProcName & " procedure, " & Chr(10) & _
  332.                           "Err_No: " & pErrNo & ", " & _
  333.                           "Err_Desc: " & pErrDesc
  334.     Resume Next
  335.  
  336. End Sub
  337.  
  338.  
  339. Sub LikeNew(Optional pClearData As Boolean = True)
  340. On Error GoTo LikeNew_err
  341.  
  342.     ' Local constants / variables
  343.    Const cProcName = "LikeNew"
  344.  
  345.     ' Select all cells
  346.    Cells.Select
  347.  
  348.     ' LikeNew format, width, height, colours and borders for all cells
  349.    With Selection
  350.         .ColumnWidth = 8.43
  351.         .RowHeight = 15
  352.         .Font.Bold = False
  353.         .NumberFormat = "General"
  354.         .Interior.ColorIndex = xlNone
  355.         .Borders(xlDiagonalDown).LineStyle = xlNone
  356.         .Borders(xlDiagonalUp).LineStyle = xlNone
  357.         .Borders(xlEdgeLeft).LineStyle = xlNone
  358.         .Borders(xlEdgeTop).LineStyle = xlNone
  359.         .Borders(xlEdgeBottom).LineStyle = xlNone
  360.         .Borders(xlEdgeRight).LineStyle = xlNone
  361.         .Borders(xlInsideVertical).LineStyle = xlNone
  362.         .Borders(xlInsideHorizontal).LineStyle = xlNone
  363.        
  364.         ' Clear data if required
  365.        If pClearData = True Then
  366.             .ClearContents
  367.         End If
  368.        
  369.     End With
  370.        
  371.     Range("A1").Select
  372.     ActiveWindow.FreezePanes = False
  373.    
  374. LikeNew_exit:
  375.     Exit Sub
  376.    
  377. LikeNew_err:
  378.     Call Gen.ErrHandler(cProcName, Err.Number, Err.Description)
  379.     Resume Next
  380.  
  381. End Sub
  382.  
  383. Function Levenshtein(ByVal string1 As String, ByVal string2 As String) As Long
  384.  
  385. Dim i As Long, j As Long
  386. Dim string1_length As Long
  387. Dim string2_length As Long
  388. Dim distance() As Long
  389.  
  390. string1 = LCase(string1)
  391. string2 = LCase(string2)
  392. string1_length = Len(string1)
  393. string2_length = Len(string2)
  394. ReDim distance(string1_length, string2_length)
  395.  
  396. For i = 0 To string1_length
  397.     distance(i, 0) = i
  398. Next
  399.  
  400. For j = 0 To string2_length
  401.     distance(0, j) = j
  402. Next
  403.  
  404. For i = 1 To string1_length
  405.     For j = 1 To string2_length
  406.         If Asc(Mid$(string1, i, 1)) = Asc(Mid$(string2, j, 1)) Then
  407.             distance(i, j) = distance(i - 1, j - 1)
  408.         Else
  409.             distance(i, j) = Application.WorksheetFunction.Min _
  410.             (distance(i - 1, j) + 1, _
  411.              distance(i, j - 1) + 1, _
  412.              distance(i - 1, j - 1) + 1)
  413.         End If
  414.     Next
  415. Next
  416.  
  417. Levenshtein = distance(string1_length, string2_length)
  418.  
  419. End Function
  420.  
  421. Function CompareDates(pDate1 As Date, pDate2 As Date) As Long
  422. On Error GoTo CompareDates_err
  423.  
  424.     ' Local constants / variables
  425.    Const cProcName = "CompareDates"
  426.     Dim v As Long  ' value
  427.    Dim y1 As Long ' year
  428.    Dim m1 As Long ' month
  429.    Dim d1 As Long ' day
  430.    Dim y2 As Long ' year
  431.    Dim m2 As Long ' month
  432.    Dim d2 As Long ' day
  433.    
  434.     ' Initialise variables
  435.    v = 0
  436.     y1 = Year(pDate1)
  437.     m1 = Month(pDate1)
  438.     d1 = Day(pDate1)
  439.     y2 = Year(pDate2)
  440.     m2 = Month(pDate2)
  441.     d2 = Day(pDate2)
  442.    
  443.     If d1 <> d2 Then
  444.         v = v + 1
  445.     End If
  446.     If m1 <> m2 Then
  447.         v = v + 1
  448.     End If
  449.     If y1 <> y2 Then
  450.         v = v + 1
  451.     End If
  452.    
  453.     CompareDates = v ^ 2
  454.    
  455. CompareDates_exit:
  456.     Exit Function
  457.    
  458. CompareDates_err:
  459.     Call Gen.ErrHandler(cProcName, Err.Number, Err.Description)
  460.     Resume Next
  461.  
  462. End Function
  463.  
  464. Function mmm_to_mm(mon As String) As String
  465. On Error GoTo mmm_to_mm_err
  466.  
  467.     ' Local constants / variables
  468.    Const cProcName = "mmm_to_mm"
  469.  
  470.     mon = LCase(mon)
  471.     If mon = "jan" Then
  472.         mmm_to_mm = "01"
  473.     ElseIf mon = "feb" Then
  474.         mmm_to_mm = "02"
  475.     ElseIf mon = "mar" Then
  476.         mmm_to_mm = "03"
  477.     ElseIf mon = "apr" Then
  478.         mmm_to_mm = "04"
  479.     ElseIf mon = "may" Then
  480.         mmm_to_mm = "05"
  481.     ElseIf mon = "jun" Then
  482.         mmm_to_mm = "06"
  483.     ElseIf mon = "jul" Then
  484.         mmm_to_mm = "07"
  485.     ElseIf mon = "aug" Then
  486.         mmm_to_mm = "08"
  487.     ElseIf mon = "sep" Then
  488.         mmm_to_mm = "09"
  489.     ElseIf mon = "oct" Then
  490.         mmm_to_mm = "10"
  491.     ElseIf mon = "nov" Then
  492.         mmm_to_mm = "11"
  493.     ElseIf mon = "dec" Then
  494.         mmm_to_mm = "12"
  495.     Else
  496.         mmm_to_mm = "error"
  497.         MsgBox ("Input not recognised, please enter the month as a 3 character string")
  498.     End If
  499.    
  500. mmm_to_mm_exit:
  501.     Exit Function
  502.    
  503. mmm_to_mm_err:
  504.     Call Gen.ErrHandler(cProcName, Err.Number, Err.Description)
  505.     Resume Next
  506. End Function
  507.  
  508. Function MinGTDate(pThreshold As Date, pRange As Range) As Date
  509. On Error GoTo MinGTDate_err
  510.  
  511.     ' Local constants / variables
  512.    Const cProcName = "MinGTDate"
  513.     Dim vMin As Date
  514.     Dim c As Variant
  515.    
  516.     'Debug.Print "Args (pThreshold and pRange) set to: " & pThreshold & " " & _
  517.                 pRange.Address
  518.    vMin = Application.Max(pRange)
  519.     'Debug.Print "vMin initialised to: " & vMin
  520.    
  521.     ' loop through range
  522.    For Each c In pRange.Cells
  523.         If c.Value > pThreshold Then
  524.             If c.Value < vMin Then
  525.                 vMin = c.Value
  526.             End If
  527.         End If
  528.     Next
  529.  
  530.     If vMin > pThreshold Then
  531.         MinGTDate = vMin
  532.     Else
  533.         MinGTDate = Empty
  534.     End If
  535.    
  536. MinGTDate_exit:
  537.     Exit Function
  538.    
  539. MinGTDate_err:
  540.     Call Gen.ErrHandler(cProcName, Err.Number, Err.Description)
  541.     Resume Next
  542. End Function
  543.  
  544.  
  545. Sub FileLoop(pDirPath As String, _
  546.              Optional pPrintToSheet = False, _
  547.              Optional pStartCellAddr = "$A$1", _
  548.              Optional pCheckCondition = False, _
  549.              Optional pFileNameContains = "xxx", _
  550.              Optional pProcToRunOnWb)
  551.  
  552. On Error GoTo PrintFileList_err
  553.              
  554.     ' Local constants / variables
  555.    Const cProcName = "FileLoop"
  556.     Dim vFileList() As String ' array for file names
  557.    Dim i As Integer          ' iterator for file name array
  558.    Dim j As Integer          ' match counter
  559.    Dim c As String
  560.     ' variables for optional param pProcToRunOnWb
  561.    Dim vFullPath As String
  562.     Dim vTmpPath As String
  563.     Dim wb As Workbook
  564.                
  565.     vFullPath = Application.ThisWorkbook.FullName
  566.     vFileList = GetFileList(pDirPath)
  567.     c = pStartCellAddr
  568.     j = 0
  569.    
  570.     For i = LBound(vFileList) To UBound(vFileList)
  571.         ' if condition is met (i.e. filename cotains text or condition is not required...
  572.        If pCheckCondition And InStr(1, vFileList(i), pFileNameContains, vbTextCompare) > 0 _
  573.            Or Not pCheckCondition Then
  574.            
  575.             ' print name to sheet if required...
  576.            If pPrintToSheet Then
  577.                 Range(c).Offset(j, 0).Value = vFileList(i)
  578.                 j = j + 1 ' increment row offset
  579.            End If
  580.        
  581.             ' open wb to run macro if required...
  582.            If pProcToRunOnWb <> "" Then
  583.                 Application.DisplayAlerts = False ' set alerts off so that macro can run in other wb
  584.                vTmpPath = pDirPath & "\" & vFileList(i)
  585.                 Set wb = Workbooks.Open(Filename:=vTmpPath)
  586.                 Workbooks(wb.Name).Activate
  587.                 Application.Run "'" & vFullPath & "'!" & pProcToRunOnWb
  588.                 wb.Close (True) ' save and close workbook
  589.                Application.DisplayAlerts = True ' set alerts back on
  590.            End If
  591.            
  592.         End If
  593.        
  594.         Debug.Print vFileList(i)
  595.     Next i
  596.    
  597.    ' clean up
  598.   Set wb = Nothing
  599.    
  600. PrintFileList_exit:
  601.     Exit Sub
  602.    
  603. PrintFileList_err:
  604.     Debug.Print "Error in ", cProcName, vbCrLf, "Err no: ", Err.Number, _
  605.                 vbCrLf, "Err Description: ", Err.Description
  606.     Resume Next
  607.  
  608. End Sub
  609.  
  610.  
  611. ' function to return an array based on files in a directory, call via
  612. ' FileLoop for output and macro options options
  613.  
  614. Function GetFileList(pDirPath As String) As Variant
  615. On Error GoTo GetFileList_err
  616.      
  617.     ' Local constants / variables
  618.    Const cProcName = "GetFileList"
  619.     Dim objFSO As Object
  620.     Dim objFolder As Object
  621.     Dim objFile As Object
  622.     Dim c As Double           ' upper bound for file name array
  623.    Dim i As Double           ' iterator for file name array
  624.    Dim vFileList() As String ' array for file names
  625.  
  626.     Set objFSO = CreateObject("Scripting.FileSystemObject")
  627.     Set objFolder = objFSO.GetFolder(pDirPath)
  628.     c = objFolder.Files.Count
  629.     i = 0
  630.    
  631.     ReDim vFileList(1 To c)  ' set bounds on file array now we know count
  632.  
  633.     'Loop through the Files collection
  634.    For Each objFile In objFolder.Files
  635.         'Debug.Print objFile.Name
  636.        i = i + 1
  637.         vFileList(i) = objFile.Name
  638.     Next
  639.      
  640.     'Clean up!
  641.    Set objFolder = Nothing
  642.     Set objFile = Nothing
  643.     Set objFSO = Nothing
  644.    
  645.     GetFileList = vFileList
  646.    
  647. GetFileList_exit:
  648.     Exit Function
  649.    
  650. GetFileList_err:
  651.     Debug.Print "Error in ", cProcName, vbCrLf, "Err no: ", Err.Number, _
  652.                 vbCrLf, "Err Description: ", Err.Description
  653.     Resume Next
  654.    
  655. End Function
  656.  
  657.  
  658. Sub Import_Text_Data(pSheet As String, _
  659.                      pPath As String, _
  660.                      pDelim As String, _
  661.                      pStartCell As String)
  662. On Error GoTo Import_Text_Data_err
  663.  
  664.     ' local constants / variables
  665.    Const cProcName = "GetFileLists"
  666.     Dim vUsePath As String
  667.     Dim vLastRow As Double
  668.     Dim vLastCol As String
  669.  
  670.     Debug.Print "Starting import process for file (" & pPath & ")"
  671.    
  672.     vUsePath = "TEXT;" & pPath
  673.     Debug.Print "Use path set to: " & vUsePath
  674.     vLastRow = Gen.LastRow(pSheet, pStartCell)
  675.     vLastCol = Gen.LastCol(pSheet, pStartCell)
  676.  
  677.     ' clear old data
  678.    ActiveWorkbook.Sheets(pSheet).Select
  679.     Range(pStartCell & ":" & vLastCol & vLastRow).ClearContents
  680.    
  681.     Debug.Print "Attempting to import data..."
  682.     With ActiveSheet.QueryTables.add(Connection:= _
  683.         vUsePath, Destination:=Range(pStartCell))
  684.         .Name = pSheet
  685.         .FieldNames = True
  686.         .RowNumbers = False
  687.         .FillAdjacentFormulas = False
  688.         .PreserveFormatting = True
  689.         .RefreshOnFileOpen = False
  690.         .RefreshStyle = xlInsertDeleteCells
  691.         .SavePassword = False
  692.         .SaveData = True
  693.         .AdjustColumnWidth = True
  694.         .RefreshPeriod = 0
  695.         .TextFilePromptOnRefresh = False
  696.         .TextFilePlatform = 1254
  697.         .TextFileStartRow = 1
  698.         .TextFileParseType = xlDelimited
  699.         .TextFileTextQualifier = xlTextQualifierDoubleQuote
  700.         .TextFileConsecutiveDelimiter = False
  701.         .TextFileTabDelimiter = False
  702.         .TextFileSemicolonDelimiter = False
  703.         .TextFileCommaDelimiter = False
  704.         .TextFileSpaceDelimiter = False
  705.         .TextFileOtherDelimiter = pDelim
  706.         .TextFileColumnDataTypes = 1
  707.         .TextFileTrailingMinusNumbers = True
  708.         .Refresh BackgroundQuery:=False
  709.     End With
  710.     Range("A1").Select
  711.  
  712. Import_Text_Data_exit:
  713.     Exit Sub
  714.    
  715. Import_Text_Data_err:
  716.        
  717.     If Err.Number = 5 Then
  718.         Debug.Print "Error no: " & Err.Number & " occurred here, error handled"
  719.         Debug.Print "Err Desc: " & Err.Description
  720.     ElseIf Err.Number = 7 Then
  721.         Debug.Print "Error no " & Err.Number & " occurred here, error handled" & vbCrLf & _
  722.             vbTab & "(Issue likely to be because there is no data in this file)."
  723.         Debug.Print "Err Desc: " & Err.Description; ""
  724.     Else
  725.         Call Gen.ErrHandler(cProcName, Err.Number, Err.Description)
  726.         Resume Next
  727.         End If
  728.     Resume Next
  729.  
  730. End Sub
  731.  
  732.  
  733. Function Fibonacci(n As Double) As Double
  734. On Error GoTo Fibonacci_err
  735.      
  736.     ' Local constants / variables
  737.    Const cProcName = "Fibonacci"
  738.  
  739.     If n <= 1 Then
  740.         Fibonacci = n
  741.     Else:
  742.         Fibonacci = Fibonacci(n - 1) + Fibonacci(n - 2)
  743.     End If
  744.  
  745. Fibonacci_exit:
  746.     Exit Function
  747.    
  748. Fibonacci_err:
  749.     Call Gen.ErrHandler(cProcName, Err.Number, Err.Description)
  750.     Resume Next
  751.    
  752. End Function
  753.  
  754.  
  755. Sub UnprotectSheetWithoutPwd()
  756.     'Breaks worksheet password protection.
  757.    Dim i As Integer, j As Integer, k As Integer
  758.     Dim l As Integer, m As Integer, n As Integer
  759.     Dim i1 As Integer, i2 As Integer, i3 As Integer
  760.     Dim i4 As Integer, i5 As Integer, i6 As Integer
  761.     On Error Resume Next
  762.     For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
  763.     For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
  764.     For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
  765.     For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126
  766.     ActiveSheet.Unprotect Chr(i) & Chr(j) & Chr(k) & _
  767.         Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
  768.         Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
  769.     If ActiveSheet.ProtectContents = False Then
  770.         MsgBox "One usable password is " & Chr(i) & Chr(j) & _
  771.             Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
  772.             Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
  773.          Exit Sub
  774.     End If
  775.     Next: Next: Next: Next: Next: Next
  776.     Next: Next: Next: Next: Next: Next
  777. End Sub
  778.  
  779.  
  780. ' still to be tested
  781. Sub DelSheets(p_sheet_to_keep)
  782.     Dim ws As Worksheet
  783.     Application.DisplayAlerts = False
  784.    
  785.     For Each ws In Worksheets
  786.         If ws.Name.lower() <> p_sheet_to_keep.lower() Then ws.Delete
  787.     Next
  788.     Application.DisplayAlerts = True
  789. End Sub
  790.  
  791.  
  792. Function FindLast(find_text As String, within_text As Range) As Double
  793.  
  794.     Dim i As Integer
  795.      
  796.     i = Len(within_text.Value) ' start at last character and work back
  797.    
  798.     Do While Mid(within_text.Value, i, 1) <> find_text
  799.         i = i - 1
  800.     Loop
  801.    
  802.     FindLast = i
  803.    
  804. End Function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement