Monday, 5 August 2013

VBA Modules: Excel: xlErrorLog v1.03a

Read this for full information on these modules

This nifty little Excel module stores errors in a log when running a long, complex macro, and then "dumps" them to an Excel worksheet when it's fnished.  There are a number of ways to do this, so this might not exactly fit your needs, and you may well already have a better solution, but this has worked for me a couple of times.

Note that "emsg" is a fairly blunt way of controlling the log macro, it's fully annotated though so it should make sense how it works.

'xlErrorLog
'v1.03a 2013-08-09 12:26

'===========================================================================
' HELP CONTACT
'===========================================================================
' Code is provided without warranty and can be stolen and amended as required.
'   Tom Parish
'   TJP@tomparish.me.uk
'   http://baldywrittencod.blogspot.com
'   DGF Help Contact: see BPMHelpContact module
'=========================================================================

'===========================================================================
' xlErrorLog
'===========================================================================
'
' errorlog("New")
'   Creates "Error Log" sheet in WB if not there already
'   --> Error Log sheet contains 2 columns:
'       Date & Time
'       Description
'
' errorlog("Description")
'   Records error with timestamp as elog([0=t|1=d], e)
'
' errorlog("Dump")
'   Dumps errors into log sheet when finished

'===========================================================================
' Additional modules required:
'===========================================================================
'   xlUtils v2.00

'=====================================================================
'  VERSION HISTORY
'=====================================================================
'   v1.03   module renamed; xlUtils bugfix; annotations improved
'   v1.02   rSort bugfix; annotations improved
'   v1.01   added option to replace duplicates
'   v1.00   created

Option Explicit

Public elog() As String

Sub errorlog(ByVal emsg As String _
    , Optional ByVal ReplaceDuplicates As Boolean = True)
'v1.03 2013-05-23 11:37
'"New" creates new errorlog
'"Dump" dumps errorlog
'"Any other message" is added to errorlog as new error
'ReplaceDuplicates = False will always add errors to list
'[ReplaceDuplicates = True] updates timestamps for existing errors
'--> Previous run record is left in place, i.e. fixed errors remain in
'    original position in the list when rerun.  If errors reoccur, the
'    timestamp is updated, and moved to below the latest heading.

Const emsgNew As String = "New"
Const emsgDump As String = "Dump"

If emsg = emsgNew Then GoTo LogNew
If emsg = emsgDump Then GoTo LogDump

Dim e As Long, etitle As String, bRD As Boolean, pp As String, tt As String
Dim rSort As Range

On Error GoTo LogNew  'errors when elog() not elog(n,n)
For e = 0 To 0
    etitle = elog(0, 0)
Next e
On Error GoTo 0
GoTo LogExists



LogNew:
'==============================
'  CREATE ERROR LOG IN MEMORY
'==============================
On Error GoTo 0
If e < 1 Then  'error log not started
    ReDim elog(1, 0) As String
    elog(0, 0) = Now()
    elog(1, 0) = ""
    Exit Sub
End If



LogExists:
'==============================
'  ADD TO ERROR LOG IN MEMORY
'==============================
e = 0
On Error GoTo AddError
    Do Until elog(0, e) = ""   'elog(0, 0) is always date & time report is run
        If elog(1, e) = emsg Then
            Exit Sub   'stops duplicate errors, also stops repeating errors found in previous errorlogs
        End If
        e = e + 1       'increments to find next available e
    Loop
AddError:
On Error GoTo 0
ReDim Preserve elog(1, e) As String
etitle = elog(1, 0)
If Left(etitle, 15) = "NO ERRORS FOUND" Then
    etitle = Mid(etitle, 4, Len(etitle)) & ":"
End If
elog(1, 0) = etitle
elog(0, e) = Now()
elog(1, e) = emsg
Exit Sub



LogDump:
'=============================
'  DUMP ERROR LOG ONTO SHEET
'=============================
Dim wsE As Worksheet
Const wsEn As String = "Error Log"
With ThisWorkbook
If xlUtils.xlU_SheetExists(wsEn, ThisWorkbook) = True Then
    For Each wsE In .Worksheets
        If wsE.Name = wsEn Then Exit For
    Next wsE
Else
    Set wsE = .Sheets.Add(After:=.Sheets(.Sheets.Count))
    With wsE
        .Name = wsEn
        With .Range("A1:B2")
            .Interior.ColorIndex = 36
            .Font.Bold = True
        End With
        .Cells(1, 1) = "ERROR LOG"
        .Cells(2, 1) = "Date & Time"
        .Cells(2, 2) = "Error"
    End With
End If
End With

Dim f As Long, n As Long, d As Long

'count existing number of rows in error log
    f = Application.CountA(wsE.Columns(1))

'!ERROR!
'dump all errors to log ONLY if errors exist
'(0,0) is always Now()
'if 1st error exists, always at (0,1) and (1,1)
'if 2nd error exists, always at (0,2) and (1,2)
'!! runtime error 9 = trying to dump before elog(0,0) started
    If Left(elog(1, 0), 15) = "NO ERRORS FOUND" Then
        MsgBox elog(0, 0) & vbLf & "Completed: no errors found"
    Else
    'elog(1,0) = "ERRORS FOUND WHEN...."
On Error GoTo DoneDump
        Do Until elog(0, e) = ""
            d = 0  'd > 0 if duplicate error found
On Error Resume Next
            d = Application.Match(elog(1, e), wsE.Columns(2), 0)
On Error GoTo DoneDump
            If e > 0 And d > 0 And ReplaceDuplicates = True Then
            'duplicate error, just update timestamp (sorted later)
                wsE.Cells(d, 1).Value = elog(0, e)
            Else
            'new error, or new list of errors, add to end of list
                With wsE.Cells(1, 1).End(xlDown).Offset(1, 0)
                    With .Offset(n, 0)
                        .Value = elog(0, e)
                        If e = 0 Then .Bold = True Else .Bold = False  'only for first message
                    End With
                    With .Offset(n, 1)
                        .Value = elog(1, e)
                        If e = 0 Then .Bold = True Else .Bold = False  'only for first message
                    End With
                End With
                n = n + 1  'next new error
            End If
            e = e + 1  'next error
        Loop
    End If
DoneDump:
On Error GoTo 0
    tt = "errorlog"
    'If Not f = Application.CountA(wsE.Columns(1)) Then
    If n > 0 Then  'new errors exist
        If ReplaceDuplicates = True Then
        'existing replaced, must be new errors added
            pp = elog(0, 0) & vbLf & "New errors - check log"
            MsgBox pp, vbExclamation, tt
        Else    'all errors added to end of list
            pp = elog(0, 0) & vbLf & "Errors - check log"
            MsgBox pp, vbExclamation, tt
        End If
    Else    'no new errors, but may be some existing errors recurring
        pp = elog(0, 0) & vbLf & "Completed: no new errors found"
        MsgBox pp, vbInformation, tt
    End If
'sort by date & time to move updated errors to the end
    With wsE
        .Activate
        Set rSort = .Cells(2, 1)
        Set rSort = .Range(rSort.End(xlToRight), rSort.End(xlDown))
        rSort.Sort Key1:=.Columns(1), Order1:=xlAscending, Header:=xlYes
    End With
'empty elog
ReDim elog(0 To 0) As String

End Sub

VBA Modules: Excel: xlClipboard v1.01

Read this for full information on these modules

It's not often that I need simple code like this now, but this is where it all started for me, saving keyboard shortcuts for Excel's Paste As [Values|Formats|Formulas].  (A bit pointless, as it turned out, because Alt, E, S, [V|T|F] is pretty easy to remember and type out!)

I adapted this module MUCH later with a great little piece of code to clear the clipboard from the Office MVPs website and another from ExcelExperts.com that "copies and pastes values" without using the clipboard.  I have to say that I never got that "vanilla" code working reliably for my needs, but the code's still pretty useful as a start point for my own ideas, so have a play with it, it might work out for you.

I've later improved on those ideas myself as I got better at VBA by creating specific functions to transfer different cell attributes (e.g. cell Validation rules).  Refer to my xlUtils module for those more advanced functions.

'xlClipboard
'v1.01a 2013-08-09 12:24

'===========================================================================
' HELP CONTACT
'===========================================================================
' Code is provided without warranty and can be stolen and amended as required.
'   Tom Parish
'   TJP@tomparish.me.uk
'   http://baldywrittencod.blogspot.com
'   DGF Help Contact: see BPMHelpContact module
'=========================================================================

'===========================================================================
' xlClipboard
'===========================================================================
'   Excel-specific and general Office Clipboard functions

'===========================================================================
' Additional modules required:
'===========================================================================
'   None

'===========================================================================
' Additional References required:
'===========================================================================
'   Microsoft Excel Object Library (if not running from Excel)

'=========================================================================
' VERSION HISTORY
'=========================================================================
'

Option Explicit

Declare Function CloseClipboard Lib "user32" () As Long
Declare Function EmptyClipboard Lib "user32" () As Long
Declare Function OpenClipboard Lib "user32" (ByVal hwnd As Long) As Long
Enum PasteAs
copyByValue = 1
copyByFormula = 2
End Enum

Sub ClearClipboard()
'source: http://officeone.mvps.org/vba/clear_clipboard.html
'needs declared module functions above
OpenClipboard 0&
EmptyClipboard
CloseClipboard
End Sub

Sub CopyPasteWithoutClipboard(rngSource As Range, rngTarget As Range, lngPasteType As PasteAs, Optional blnTranspose As Boolean = False)
'source: http://excelexperts.com/copy-values-vba
'Do not use this procedure with filtered/hidden rows as it considers all hidden/filtered cells
'While transposing only values can be transposed not formulae
'Merged cells are not considered

Dim lngCalc As Long
Dim lngEvents As Long

With Application
lngCalc = .Calculation
lngEvents = .EnableEvents
If Not .EnableEvents = False Then .EnableEvents = False
If Not .Calculation = xlCalculationManual Then .Calculation = xlCalculationManual
End With

Select Case lngPasteType
Case copyByValue
If blnTranspose Then
rngTarget.Resize(rngSource.Columns.Count, rngSource.Rows.Count).Value = Application.Transpose(rngSource.Value)
Else
rngTarget.Resize(rngSource.Rows.Count, rngSource.Columns.Count).Value = rngSource.Value
End If
Case copyByFormula
If blnTranspose Then
rngTarget.Resize(rngSource.Columns.Count, rngSource.Rows.Count).Value = Application.Transpose(rngSource.Value)
Else
rngTarget.Resize(rngSource.Rows.Count, rngSource.Columns.Count).Formula = rngSource.FormulaR1C1
End If
End Select

With Application
If Not .Calculation = lngCalc Then .Calculation = lngCalc
If Not .EnableEvents = lngEvents Then .EnableEvents = lngEvents
End With

End Sub
Sub Test_CopyPasteWithoutClipboard()
'source: http://excelexperts.com/copy-values-vba
'Call CopyPasteWithoutClipboard(Sheet1.Range("A1").CurrentRegion, Sheet2.Range("A1"), copyByValue)
End Sub









Sub PasteComments()
'
' Keyboard Shortcut: Ctrl+Shift+C
'
    Selection.PasteSpecial Paste:=xlPasteComments, Operation:=xlNone, _
        SkipBlanks:=False, Transpose:=False
End Sub

Sub PasteFormulas()
'
' Keyboard Shortcut: Ctrl+Shift+Q
'
    Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
        SkipBlanks:=False, Transpose:=False
End Sub

Sub PasteValues()
'
' Keyboard Shortcut: Ctrl+Shift+V
'
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

End Sub

Sub PasteFormats()
'
' Keyboard Shortcut: Ctrl+Shift+T
'
    Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
        SkipBlanks:=False, Transpose:=False
      
End Sub

Sub Paste_Transpose()
'
' Keyboard Shortcut: Ctrl+Shift+E
'
    Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
        False, Transpose:=True

End Sub

VBA Modules: modAppsFirefox v3.04

NB: updated 2013-09-02 - v3 works with modProcedures

Read this for full information on these modules

Another deadly simple and endlessly useful module, lifted from Mr Excel.  Note that you can do a lot of things automatically with Firefox if you install the LastPass addon, which stores your site login information and automatically logs in to a site.  This means you can easily download a remote file from a web server somewhere just by opening the URL for the file using ff_GetDownload.  I don't think it's usually necessary to log in to the site first, LastPass will handle that, but it certainly doesn't do any harm, it just opens an extra FF tab.

When downloading a file, Firefox will save the actual filename.ext with 0 bytes as a placeholder, and create filename.ext.part which is the actual downloading file.  When FF completes the download, it'll delete the original filename.ext file, and rename the filename.ext.part file to filename.ext.  So when it's completed the download, filename.ext will instantly be > 0 bytes.

Code for Sleep:
'source: http://www.vboffice.net/sample.html?mnu=2&lang=en&smp=56&cmd=showitem&pub=6
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliSeconds As Long)

Private Const fwLoginURL As String = "http://forwin.dhl.com"  'can be set to any site login

Public Sub Sleep_Test()
'source: http://www.vboffice.net/sample.html?mnu=2&lang=en&smp=56&cmd=showitem&pub=6
  Sleep 3000
  MsgBox "Hello"
End Sub

This uses code from modSpecialFolders to find the location of the user's Downloads folder but you can also hard-code the path if preferred.

I've never managed to get Internet Explorer to work in the same way, (un)surprisingly Microsoft just don't make it easy.  There's plenty of support online if you really must use IE, e.g. if your corporate policy doesn't permit LastPass for automatic logins.

'modAppsFirefox
'v3.04 2013-09-20 13:32

'===========================================================================
' HELP CONTACT
'===========================================================================
' Code is provided without warranty and can be stolen and amended as required.
'   Tom Parish
'   TJP@tomparish.me.uk
'   http://baldywrittencod.blogspot.com
'   DGF Help Contact: see BPMHelpContact module
'=========================================================================

'===========================================================================
' modAppsFirefox
'===========================================================================
'   macros to load URL in Firefox, based on open source code:
'   http://www.mrexcel.com/forum/excel-questions/568204-opening-url-firefox-excel.html
'
'   Automatically determines standard Windows 7 Downloads folder location.
'   Specify custom Downloads folder location as Private Const below.
'
'   Save your site login details with the LastPass addon, and make sure it's
'   set to always autologin to the site.

'===========================================================================
' Additional modules required:
'===========================================================================
'   modFile v1.03
'
'   Code included from other modules:
'      [modSpecialFolders]

'===========================================================================
' Additional References required:
'===========================================================================
'   None

'===========================================================================
' External applications required:
'===========================================================================
'   Mozilla Firefox
'   LastPass Firefox Addon

'===========================================================================
' VERSION HISTORY
'===========================================================================
'   v3.04   minor edit, variable name change in modFile
'   v3.03   ffGetSimultDownloads counts .part files in DLs folder
'   v3.02   always wait for completion if running outside office hours
'   v3.01   ffGetDownload = ffFileURL for queued downloads when max dl reached
'   v3.00   works with modProcedures
'   v2.01   ff_GetDownload: added ffLoginTime and improved ffSleepTime usage
'                           added ErrorHandlerNoFile
'   v2.00   transferred code from modSpecialFolders
'   v1.06   ff_GetDownload: bugfix, potentially .part file is newer
'   v1.05   ff_GetDownload: redesigned download completion detection
'           extended ffSleepTime
'           improved annotations
'   v1.04   added Private Const ffSleepTime
'   v1.03   ff_GetDownload: only waits for site login if necessary
'   v1.02   transferred ff_GetDownload from modForwin (was Forwin_GetDownload)
'   v1.01aa renamed modAppsFirefox
'   v1.01a  annotations only
'   v1.01   refers modSpecialFolders
'   v1.00   original code from source:
'           http://www.mrexcel.com/forum/excel-questions/568204-opening-url-firefox-excel.html

Option Explicit

Private Const ffSpecifyDownloadFolder As String = ""
'source: http://www.vboffice.net/sample.html?mnu=2&lang=en&smp=56&cmd=showitem&pub=6
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliSeconds As Long)

Private Const ffLoginTime As Long = 20000  'v2.01, 10s is too short to allow login and file transfer to begin
'!! if 1000ms causes issues, try a longer time
Private Const ffSleepTime As Long = 1000  'v1.05, ms, i.e. 10000ms = 10s

'NB: Firefox can only run N simultaneous downloads, must store further URLs as Download procedures
'!! may need to improve this by clearing completed downloads?  (i.e. run modProcedures.mp_Run_Procedures on sheets 1 and 2)
Public Const ffMaxSimultDownloads As Byte = 5       'v3.03 'v3.01
Private Const ffDownloadWaitTime As Long = 60000    'v3.01 - only if ffWaitForCompletion = True

Private Const ffOffHrsMin As Byte = 9     'ALWAYS waits if Now < this
Private Const ffOffHrsMax As Byte = 18    'ALWAYS waits if Now > this
Private Const ffWEDay1 As String = "Sat"  'ALWAYS waits if running on Sat
Private Const ffWEDay2 As String = "Sun"  'change to Mon or "" as applicable to your country

Public ffCompleted As Boolean  'v3.00


'=================================================================================================
'=================================================================================================
'=================================================================================================
'=================================================================================================

'
'   Code from modSpecialFolders module:
'

'http://answers.microsoft.com/en-us/office/forum/office_2010-customize/how-2-refer-to-desktop/97eba910-54c9-409f-9454-6d7c8d54d009
Private Declare Function SHGetSpecialFolderLocation _
                         Lib "shell32" (ByVal hwnd As Long, _
                                        ByVal nFolder As Long, ppidl As Long) As Long

Private Declare Function SHGetPathFromIDList _
                         Lib "shell32" Alias "SHGetPathFromIDListA" _
                             (ByVal Pidl As Long, ByVal pszPath As String) As Long

Private Declare Sub CoTaskMemFree Lib "ole32" (ByVal pvoid As Long)

'Desktop
Private Const CSIDL_INTERNET = &H1 'Internet Explorer (icon on desktop)
Private Const CSIDL_PROGRAMS = &H2 'Start Menu\Programs
Private Const CSIDL_CONTROLS = &H3 'My Computer\Control Panel
Private Const CSIDL_PRINTERS = &H4 'My Computer\Printers
Private Const CSIDL_PERSONAL = &H5 'My Documents
Private Const CSIDL_FAVORITES = &H6 '<user name>\Favorites
Private Const CSIDL_STARTUP = &H7 'Start Menu\Programs\Startup
Private Const CSIDL_RECENT = &H8 '<user name>\Recent
Private Const CSIDL_SENDTO = &H9 '<user name>\SendTo
Private Const CSIDL_BITBUCKET = &HA '<desktop>\Recycle Bin
Private Const CSIDL_STARTMENU = &HB '<user name>\Start Menu
Private Const CSIDL_DESKTOPDIRECTORY = &H10 '<user name>\Desktop
Private Const CSIDL_DRIVES = &H11 'My Computer
Private Const CSIDL_NETWORK = &H12 'Network Neighborhood
Private Const CSIDL_NETHOOD = &H13 '<user name>\nethood
Private Const CSIDL_FONTS = &H14 'Windows\fonts
Private Const CSIDL_TEMPLATES = &H15
Private Const CSIDL_COMMON_STARTMENU = &H16 'All Users\Start Menu
Private Const CSIDL_COMMON_PROGRAMS = &H17 'All Users\Programs
Private Const CSIDL_COMMON_STARTUP = &H18 'All Users\Startup
Private Const CSIDL_COMMON_DESKTOPDIRECTORY = &H19 'All Users\Desktop
Private Const CSIDL_APPDATA = &H1A '<user name>\Application Data
Private Const CSIDL_PRINTHOOD = &H1B '<user name>\PrintHood
Private Const CSIDL_LOCAL_APPDATA = &H1C '<user name>\Local Settings\Application Data (non roaming)
Private Const CSIDL_ALTSTARTUP = &H1D 'non localized startup
Private Const CSIDL_COMMON_ALTSTARTUP = &H1E 'non localized common startup
Private Const CSIDL_COMMON_FAVORITES = &H1F
Private Const CSIDL_INTERNET_CACHE = &H20
Private Const CSIDL_COOKIES = &H21
Private Const CSIDL_HISTORY = &H22
Private Const CSIDL_COMMON_APPDATA = &H23 'All Users\Application Data
Private Const CSIDL_WINDOWS = &H24 'Windows Directory
Private Const CSIDL_SYSTEM = &H25 'System Directory
Private Const CSIDL_PROGRAM_FILES = &H26 'C:\Program Files
Private Const CSIDL_MYPICTURES = &H27 'C:\Program Files\My Pictures
Private Const CSIDL_PROFILE = &H28 'USERPROFILE
Private Const CSIDL_SYSTEMX86 = &H29 'x86 system directory on RISC
Private Const CSIDL_PROGRAM_FILESX86 = &H2A 'x86 C:\Program Files on RISC
Private Const CSIDL_PROGRAM_FILES_COMMON = &H2B 'C:\Program Files\Common
Private Const CSIDL_PROGRAM_FILES_COMMONX86 = &H2C 'x86 Program Files\Common on RISC
Private Const CSIDL_COMMON_TEMPLATES = &H2D 'All Users\Templates
Private Const CSIDL_COMMON_DOCUMENTS = &H2E 'All Users\Documents
Private Const CSIDL_COMMON_ADMINTOOLS = &H2F 'All Users\Start Menu\Programs\Administrative Tools
Private Const CSIDL_ADMINTOOLS = &H30 '<user name>\Start Menu\Programs\Administrative Tools
Private Const CSIDL_CONNECTIONS = &H31 'Network and Dial-up Connections
Private Const MAX_PATH = 260
Private Const NOERROR = 0

Private Function SpecFolder(ByVal lngFolder As Long) As String
Dim lngPidlFound As Long
Dim lngFolderFound As Long
Dim lngPidl As Long
Dim strPath As String

strPath = Space(MAX_PATH)
lngPidlFound = SHGetSpecialFolderLocation(0, lngFolder, lngPidl)
If lngPidlFound = NOERROR Then
    lngFolderFound = SHGetPathFromIDList(lngPidl, strPath)
    If lngFolderFound Then
        SpecFolder = Left$(strPath, _
                           InStr(1, strPath, vbNullChar) - 1)
    End If
End If
CoTaskMemFree lngPidl
End Function

Sub Test_OpenFireFoxNewTab()
  OpenInFireFoxNewTab "http://www.mrexcel.com/forum/forumdisplay.php?f=10"
End Sub

Sub OpenInFireFoxNewTab(url As String)
'v2.00 2013-08-09 11:59
  Dim pathFireFox As String
  pathFireFox = SpecFolder(CSIDL_PROGRAM_FILES) & "\Mozilla Firefox\firefox.exe" 'v1.01
  If Dir(pathFireFox) = "" Then pathFireFox = "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
  If Dir(pathFireFox) = "" Then pathFireFox = "C:\Program Files\Mozilla Firefox\firefox.exe"
  If Dir(pathFireFox) = "" Then
    MsgBox "FireFox Path Not Found", vbCritical, "Macro Ending"
    Exit Sub
  End If
  Shell """" & pathFireFox & """" & " -new-tab " & url, vbHide
End Sub

Function ff_GetDownload(ByVal ffFileURL As String, ByVal ffFileExt As String _
    , Optional ByVal ffNewFileName As String, Optional ByVal ffWaitForCompletion As Boolean) As String
'v3.04 2013-09-20 13:32
'launches FireFox, logs in to web server, downloads Filename.FileExt
'then renames to specified [ffNewFileName] OR [cDefaultFilename].[ffFileExt]
'reports back new path & filename (NB: default is [userpath]\Downloads\[cDefaultFilename].[ffFileExt])
'v3.00 can report back temporary filename for use with modProcedures

ffCompleted = False  'v3.00

Const ffLoginURL As String = ""  'optional, forces login before launching actual URL
Dim sCount As Byte  'counts and limits number of sleeps

On Error Resume Next  'validity checks done at end

If ffGetCurrentSimultDownloads < ffMaxSimultDownloads Then  'v3.01
    'download this file
   
    'launch web server in FF (automatic login is handled with LastPass addon)
        If ffLoginURL <> "" Then
            modAppsFirefox.OpenInFireFoxNewTab ffLoginURL
        'wait for LastPass to log in
            Sleep ffLoginTime
        End If
   
    'launch URL to download (FF will automatically download files to user's specified Downloads folder)
    Dim dCreatedDate As Double
        dCreatedDate = Now()  'records date & time file creation was started, prevents false "newset file" matches
        modAppsFirefox.OpenInFireFoxNewTab ffFileURL
   
    'minimum pause for LastPass to log in to site, and file transfer to begin
    '!! take care: if this causes the wrong file to be detected, increase ffLoginTime
        Sleep ffLoginTime
   
    'get file name for NEWEST file in Downloads folder
    'Firefox creates file.ext.part AND file.ext
        Dim pthDL As String, ffDownloadingFile As String
        pthDL = ffSpecifyDownloadFolder  'can specify path as Private Const
        If pthDL = "" Then pthDL = Replace(SpecFolder(CSIDL_PERSONAL), "\Documents", "\Downloads\") 'also adds trailing slash
FindNewestFile:
        ffDownloadingFile = modFile.mfLoopThroughFilesInAFolder(mfPath:=pthDL, mfNewestFile:=True, mfNewestFileNewerThan:=dCreatedDate)  'v3.04
        If ffDownloadingFile = "" Then
        'newest file not found, wait then try again
            sCount = sCount + 1
            Sleep ffSleepTime
            If sCount < 10 Then GoTo FindNewestFile  'prevent endless loop
        End If
        If ffDownloadingFile = "" Then GoTo ErrorHandlerNoFile
        ffDownloadingFile = Replace(ffDownloadingFile, ".part", "")  'catch potential errors due to .part file being newer
   
    'whilst downloading, file.ext placeholder will exist with 0 bytes, file.ext.part is temporary downloading file
    'on completion, file.ext wil be deleted, then file.ext.part will be renamed, so file.ext will be >0 bytes
    'v3.02 regardless of user setting, always wait for completion if running outside office hours
    If ffWaitForCompletion = True _
    Or Hour(Now()) < ffOffHrsMin _
    Or Hour(Now()) >= ffOffHrsMax _
    Or Format(Now(), "Ddd") = ffWEDay1 _
    Or Format(Now(), "Ddd") = ffWEDay2 _
    Then
        Dim f1 As Double
    On Error Resume Next
        f1 = FileLen(ffDownloadingFile)
        Do While f1 = 0
        'when download completes, ffDownloadingFile is deleted (i.e. error) then reappears with f1 > 0
            f1 = FileLen(ffDownloadingFile)
        Loop
    On Error GoTo 0
        ffCompleted = True
   
    'rename downloaded file if specified
    'NB: renaming .csv to .xls will cause you problems!
        If ffNewFileName <> "" Then
        'use specified filename
            ff_GetDownload = ffNewFileName
        Else
        'use default download filename
            Const cDefaultFilename As String = "Downloaded Web Server Report."  ' & ffFileExt
            Const cPrd As String = "."
            ffFileExt = Replace(LCase(ffFileExt), cPrd, "")
            ff_GetDownload = cDefaultFilename & ffFileExt
        End If
    'before renaming download file, kill target filename, if it exists
        If Dir(ff_GetDownload) <> "" Then Kill ff_GetDownload
    'rename/move downloaded file
        Name ffDownloadingFile As ff_GetDownload
   
   
    'validity check to confirm download completed
        If Dir(ff_GetDownload) = "" Then
        'downloaded file doesn't exist, something went wrong
            MsgBox "Downloaded file not found", vbCritical, "Error in ff_GetDownload"
            GoTo ErrorHandlerNoFile
        End If
   
    Else  'ffWaitForCompletion = False AND during business hours
    'don't wait, store the first N download procedures for processing later
    'NB: capture this in parent macro
        ff_GetDownload = ffDownloadingFile
    'NB: ff_GetDownload <> ffNewFileName
   
    End If

Else
'too many simultaneous downloads already, store this download URL for later
'NB: must capture this in parent macro
    ff_GetDownload = ffFileURL

End If

On Error GoTo 0
Exit Function

ErrorHandlerNoFile:
ff_GetDownload = ""
End Function

Function ffGetCurrentSimultDownloads() As Byte
'v3.03 2013-09-13 11:05
'counts .part files in Downloads folder
'Firefox can only run ffMaxSimultDownloads

Dim pthDL As String
Const ffDLpartfile As String = ".part"
pthDL = ffSpecifyDownloadFolder  'can specify path as Private Const
If pthDL = "" Then pthDL = Replace(SpecFolder(CSIDL_PERSONAL), "\Documents", "\Downloads\") 'also adds trailing slash
ffGetCurrentSimultDownloads = modFile.mfLoopThroughFilesInAFolder(mfPath:=pthDL _
    , mfSearchString:=ffDLpartfile, mfCountMatches:=True)

End Function

VBA Modules: modFile v1.05

Read this for full information on these modules

This module contains a few useful VBA file and folder functions.  I've lifted most of this from StackOverflow and Mr Excel and other forums, it's all fairly simple stuff.

'modFile
'v1.05 2013-09-20 13:33

'===========================================================================
' HELP CONTACT
'===========================================================================
' Code is provided without warranty and can be stolen and amended as required.
'   Tom Parish
'   TJP@tomparish.me.uk
'   http://baldywrittencod.blogspot.com
'   DGF Help Contact: see BPMHelpContact module
'=========================================================================

'===========================================================================
' modFile
'===========================================================================
'   Provides various VBA file & folder functions

'===========================================================================
' Additional modules required:
'===========================================================================
'   None

'===========================================================================
' Additional References required:
'===========================================================================
'   None

'===========================================================================
' External applications required:
'===========================================================================
'   None

'=========================================================================
' VERSION HISTORY
'=========================================================================
'   v1.05   mfLoopThroughFilesInAFolder: bugfix for NewerThan and variable name change
'   v1.04   mfLoopThroughFilesInAFolder: function reports back Variant
'           mfLoopThroughFilesInAFolder: will count pattern matches
'   v1.03a  annotations only
'   v1.03   added mfLoopThroughFilesInAFolder
'           added mfGetDateCreated
'   v1.02a  annotations only
'   v1.02   addded mfGetFileExtension
'   v1.01   added mf prefix to macronames
'************************************************************************
'   v1.00   created from Allen Browne original code

Option Explicit

Function mfFileExists(ByVal strFile As String, Optional bFindFolders As Boolean) As Boolean
'Purpose:   Return True if the file exists, even if it is hidden.
'Arguments: strFile: File name to look for. Current directory searched if no path included.
'           bFindFolders. If strFile is a folder, mfFileExists() returns False unless this argument is True.
'Note:      Does not look inside subdirectories for the file.
'Author:    Allen Browne. http://allenbrowne.com June, 2006.
Dim lngAttributes As Long

'Include read-only files, hidden files, system files.
lngAttributes = (vbReadOnly Or vbHidden Or vbSystem)

If bFindFolders Then
    lngAttributes = (lngAttributes Or vbDirectory) 'Include folders as well.
Else
    'Strip any trailing slash, so Dir does not look inside the folder.
    Do While Right$(strFile, 1) = "\"
        strFile = Left$(strFile, Len(strFile) - 1)
    Loop
End If

'If Dir() returns something, the file exists.
On Error Resume Next
mfFileExists = (Len(Dir(strFile, lngAttributes)) > 0)

End Function

Function mfFolderExists(strPath As String) As Boolean
    On Error Resume Next
    mfFolderExists = ((GetAttr(strPath) And vbDirectory) = vbDirectory)
End Function

Function mfTrailingSlash(varIn As Variant) As String
    If Len(varIn) > 0 Then
        If Right(varIn, 1) = "\" Then
            mfTrailingSlash = varIn
        Else
            mfTrailingSlash = varIn & "\"
        End If
    End If
End Function

Function mfGetFileExtension(ByVal mfFileName As String) As String
'v1.02 2013-04-12 14:58
'reports characters after and including the LAST fullstop/period
'e.g. "File Name v3.45.xlsm" result is ".xlsm"

Const cPrd As String = "."
Dim b As Byte, c As Byte, pp As String, tt As String
b = InStr(1, mfFileName, cPrd) 'find first period in string
If b = 0 Then
'no periods found = no file extension
    mfGetFileExtension = cPrd
Else
'make sure b is the last period in string
    c = b
    Do Until c = 0
        c = InStr(b + 1, mfFileName, cPrd)
        If c <> 0 Then b = c
    Loop
    mfGetFileExtension = cPrd & Right(mfFileName, Len(mfFileName) - b)
End If
End Function

Function mfGetDateCreated(ByVal mfPathAndFileName As String) As Double
'v1.03 2013-07-18 16:05
'source: http://www.mrexcel.com/forum/excel-questions/73458-read-external-file-properties-date-created-using-visual-basic-applications.html

    Dim oFS As Object

    'This creates an instance of the MS Scripting Runtime FileSystemObject class
    Set oFS = CreateObject("Scripting.FileSystemObject")

    'MsgBox mfPathAndFileName & " was created on " & oFS.GetFile(mfPathAndFileName).DateCreated
    mfGetDateCreated = oFS.GetFile(mfPathAndFileName).DateCreated

    Set oFS = Nothing

End Function

Function mfLoopThroughFilesInAFolder(ByVal mfPath As String _
    , Optional ByVal mfSearchString As String = "" _
    , Optional ByVal mfNewestFile As Boolean = False, Optional ByVal mfNewestFileNewerThan As Double _
    , Optional ByVal mfCountMatches As Boolean)
'v1.05 2013-09-20 13:33
'original source: http://stackoverflow.com/questions/10380312/loop-through-files-in-a-folder-using-vba
'searches in order of variables specified, only ever searches one variable
'Usage:
'   if mfSearchString is specified, searches for pattern match in filename
'   if mfNewestFile is specified, searches for newest file created
'   if mfCountMatches is True, counts pattern matches, mfSearchString is also required
'       NB: mfNewestFileNewerThan [i.e. Now()] should also be specified as a validity check for search range

Const cBsl As String = "\"
If Right(mfPath, 1) <> cBsl Then mfPath = mfPath & cBsl

Dim mfFile As Variant

If mfSearchString = "" And mfNewestFile = False Then  'mfFilenameMinLen = 0 And
    MsgBox "Must search for filename string OR minimum length of filename OR look for newest file"
    Exit Function

ElseIf mfSearchString <> "" Then
'search for pattern match
    If mfCountMatches Then
    'count pattern matches
        mfFile = Dir(mfPath)
        While (mfFile <> "")
            If InStr(mfFile, mfSearchString) > 0 Then
                'MsgBox "found by pattern match: " & mfPath & mfFile
                mfLoopThroughFilesInAFolder = mfLoopThroughFilesInAFolder + 1
            End If
            mfFile = Dir
        Wend
    Else
    'find first file
        mfFile = Dir(mfPath)
        While (mfFile <> "")
            If InStr(mfFile, mfSearchString) > 0 Then
                'MsgBox "found by pattern match: " & mfPath & mfFile
                mfLoopThroughFilesInAFolder = mfPath & mfFile
                Exit Function
            End If
            mfFile = Dir
        Wend
    End If

'ElseIf mfFilenameMinLen <> 0 Then  'can't see why this would ever be used
'    mfFile = Dir(mfPath)
'    While (mfFile <> "")
'        If Len(mfFile) > 0 Then
'            'MsgBox "found by min length of filename: " & mfPath & mfFile
'            mfLoopThroughFilesInAFolder = mfPath & mfFile
'            Exit Function
'        End If
'        mfFile = Dir
'    Wend

ElseIf mfNewestFile = True Then
'search for newest file
    Dim mfCDthisfile As Double, mfCDnewest As Double
    mfFile = Dir(mfPath)
    If mfFile = "" Then GoTo ErrorHandler  'catches errors if no files found in path
On Error GoTo ErrorHandler  'catches errors if path invalid or some other error in mfGetDateCreated
    mfCDthisfile = mfGetDateCreated(mfPath & mfFile)
    If mfNewestFileNewerThan = 0 Then mfCDnewest = mfCDthisfile Else mfCDnewest = mfNewestFileNewerThan 'helps to limit searching for newer files than this one
On Error GoTo 0
    While (mfFile <> "")
        mfCDthisfile = mfGetDateCreated(mfPath & mfFile)
        If mfCDthisfile > mfCDnewest Then
            mfCDnewest = mfCDthisfile
            mfLoopThroughFilesInAFolder = mfPath & mfFile  'always newest file, .PART file is created FIRST
        End If
        mfFile = Dir
    Wend
'NB: returns "" if no newest file found
End If

Exit Function
ErrorHandler:
MsgBox "Error in mfLoopThroughFilesInAFolder: no files found in path" & vbLf & vbLf & mfPath
End Function

VBA Modules: modEmail v1.09



Read this for full information on these modules

This deadly simple piece of code will send an email via Outlook.

Original source from Microsoft support site
'modEmail
'v1.09 2013-11-12 10:36

'===========================================================================
' HELP CONTACT
'===========================================================================
' Code is provided without warranty and can be stolen and amended as required.
'   Tom Parish
'   TJP@tomparish.me.uk
'   http://baldywrittencod.blogspot.com
'   DGF Help Contact: see BPMHelpContact module
'=========================================================================

'===========================================================================
' modEmail
'===========================================================================
'   Routines for sending emails.

'===========================================================================
' Additional modules required:
'===========================================================================
'   None

'===========================================================================
' Additional References required:
'===========================================================================
'   None

'===========================================================================
' External applications required:
'===========================================================================
'   None

'=========================================================================
' VERSION HISTORY
'=========================================================================
'   v1.09   bugfix - AttachmentPaths as string <> ""
'           upgrade from v1.08 essential
'*************************************************************************
'   v1.08   bugfix - dim AttachmentPaths as string
'*************************************************************************
'   v1.07   up to 3 attachments
'   v1.06   bugfix - multiple To/CC/BCC didn't resolve if separated by ";"
'   v1.05   bugfix - multiple To/CC/BCC recipients didn't resolve
'*************************************************************************
'   v1.04   bugfix - upgrade advised
'   v1.03   bugfix - upgrade essential
'*************************************************************************
'   v1.02a  annotations only
'   v1.02   added cDefaultEmail
'   v1.01   late bound references
'   v1.00   SendEmail: code adapted from original source
'           http://support.microsoft.com/kb/161088

Option Explicit

'default email address for Trigger Failure and if recipient is specified as "" (mainly for testing)
Public Const cDefaultEmail As String = "bpm.gb@dhl.com"  'v1.04

Private Enum olDefaultFolders
    olFolderCalendar = 9
    olFolderContacts = 10
    olFolderDeletedItems = 3
    olFolderDrafts = 16
    olFolderInbox = 6
    olFolderJournal = 11
    olFolderJunk = 23
    olFolderNotes = 12
    olFolderOutbox = 4
    olFolderSentMail = 5
    olFolderTasks = 13
    olPublicFoldersAllPublicFolders = 18
    olFolderConflicts = 19
    olFolderLocalFailures = 21
    olFolderServerFailures = 22
    olFolderSyncIssues = 20
End Enum

Private Enum olItemType
    olAppointmentItem = 1
    olContactItem = 2
    olDistributionListItem = 7
    olJournalItem = 4
    olMailItem = 0
    olNoteItem = 5
    olPostItem = 6
    olTaskItem = 3
End Enum

Function SendEmail(ByVal Email_Recipient As String, Optional ByVal Email_RecipientCC As String _
    , Optional ByVal Email_RecipientBCC As String, Optional ByVal Email_Subject As String _
    , Optional ByVal Email_BodyText As String, Optional ByVal DisplayMsg As Boolean = False _
    , Optional AttachmentPath As String, Optional AttachmentPath2 As String, Optional AttachmentPath3 As String _
    ) As Byte
'v1.09 2013-11-12 10:36
'results: 0=success, 1=fail
'original source: http://support.microsoft.com/kb/161088
'v1.05 bugfix: http://stackoverflow.com/questions/13019651/automated-email-generation-not-resolving-multiple-recipients

On Error GoTo SendEmailError

Dim objOutlook As Object        'Outlook.Application
'Dim objOutlookMsg 'As Object     'Outlook.MailItem
Dim objOutlookRecip As Object   'Outlook.Recipient
Dim objOutlookAttach As Object  'Outlook.Attachment
'http://stackoverflow.com/questions/13019651/automated-email-generation-not-resolving-multiple-recipients
Dim EmailList As Variant, NumEmails As Long, AddEmailLoop As Long

' Create the Outlook session.
If InStr(Application.Name, "Outlook") = 0 Then
    Set objOutlook = CreateObject("Outlook.Application")
Else
    Set objOutlook = Application
End If

' Create the message.
'Set objOutlookMsg = objOutlook.CreateItem(0) 'olMailItem
Set objOutlook = objOutlook.CreateItem(0) 'olMailItem

'With objOutlookMsg
With objOutlook
    ' Add the To recipient(s) to the message.
    If Email_Recipient = "" Then
        Set objOutlookRecip = .Recipients.Add(cDefaultEmail)  'for testing/blunt force only
    Else
    'http://stackoverflow.com/questions/13019651/automated-email-generation-not-resolving-multiple-recipients
        Email_Recipient = Replace(Email_Recipient, ";", "; ")  'v1.06
        EmailList = Split(Email_Recipient, ";")
        NumEmails = UBound(EmailList)
        For AddEmailLoop = 0 To NumEmails
            Set objOutlookRecip = .Recipients.Add(EmailList(AddEmailLoop))
            objOutlookRecip.Type = 1 'olTo
            objOutlookRecip.Resolve
        Next
    End If

    ' Add the CC recipient(s) to the message.
    If Email_RecipientCC <> "" Then
        Email_RecipientCC = Replace(Email_RecipientCC, ";", "; ")  'v1.06
        EmailList = Split(Email_RecipientCC, "; ")
        NumEmails = UBound(EmailList)
        For AddEmailLoop = 0 To NumEmails
            Set objOutlookRecip = .Recipients.Add(EmailList(AddEmailLoop))
            objOutlookRecip.Type = 2 'olCC
            objOutlookRecip.Resolve
        Next
    End If
  
   ' Add the BCC recipient(s) to the message.
    If Email_RecipientBCC <> "" Then
        Email_RecipientBCC = Replace(Email_RecipientBCC, ";", "; ")  'v1.06
        EmailList = Split(Email_RecipientBCC, "; ")
        NumEmails = UBound(EmailList)
        For AddEmailLoop = 0 To NumEmails
            Set objOutlookRecip = .Recipients.Add(EmailList(AddEmailLoop))
            objOutlookRecip.Type = 3 'olBCC
            objOutlookRecip.Resolve
        Next
    End If

   ' Set the Subject, Body, and Importance of the message.
   .Subject = Email_Subject
   .Body = Email_BodyText & vbCrLf & vbCrLf
   .Importance = 2  'olImportanceHigh  'High importance

   ' Add attachments to the message.
   If AttachmentPath <> "" Then  'v1.09
       Set objOutlookAttach = .Attachments.Add(AttachmentPath)
   End If
   If AttachmentPath2 <> "" Then  'v1.07
       Set objOutlookAttach = .Attachments.Add(AttachmentPath2)
   End If
   If AttachmentPath3 <> "" Then
       Set objOutlookAttach = .Attachments.Add(AttachmentPath3)
   End If

   ' Resolve each Recipient's name.  'v1.06 now resolved separately on addition
'   For Each objOutlookRecip In .Recipients
'       objOutlookRecip.Resolve
'   Next

   ' Should we display the message before sending?
   If DisplayMsg Then
       .Display
   Else
       .Save
       .Send
   End If
End With

Set objOutlook = Nothing
SendEmail = 0  'no error
Exit Function

SendEmailError:
SendEmail = 1  'general failure
End Function

VBA Modules: Excel: xlCodeNames v1.00

Read this for full information on these modules

This code is adapted from the original information by Chip Pearson.  PLEASE READ THE ORIGINAL INFORMATION BEFORE USING THIS, you can quite easily break Excel if you don't know what you're doing.


Option Explicit
'v1.00 2013-05-02 13:10
'Reference http://www.cpearson.com/excel/codemods.htm
'VBA code to update sheet, workbook, etc. code names

Sub vbProjectCodeName(ByVal NewName As String, ByRef wb As Workbook)
wb.VBProject.Name = NewName
End Sub

Sub vbWorkbookCodeName(ByVal NewName As String, ByRef wb As Workbook)
'!! use with caution, default object name is ThisWorkbook (you can always reset it afterwards)
wb.VBProject.VBComponents(wb.CodeName).Name = NewName
End Sub

Sub vbWorksheetCodeName(ByVal NewName As String, ByRef wb As Workbook, ByRef ws As Worksheet)
wb.VBProject.VBComponents(ws.CodeName).Name = NewName
End Sub

VBA Modules: modCheckUsers v2.02

Read this for full information on these modules

Now this is one I have designed myself from scratch.

At its simplest level, CU_UserID("someID") checks for a match in the Windows UserID, which is great if you distribute an XLSM file and don't want Event macros to run for anyone else but yourself.

As a more complex function, CU_Public will check the current user against a specified file list of "valid users" which should be held in an Excel (or CSV) validation file, stored somewhere publicly accessible, e.g. a read-only SharePoint site or some other web URL.

Makes use of code copied from modSpecialFolders

'modCheckUsers
'v2.02 2013-10-29 10:34

'===========================================================================
' HELP CONTACT
'===========================================================================
' Code is provided without warranty and can be stolen and amended as required.
'   Tom Parish
'   TJP@tomparish.me.uk
'   http://baldywrittencod.blogspot.com
'   DGF Help Contact: see BPMHelpContact module
'=========================================================================

'===========================================================================
' modCheckUsers
'===========================================================================
'   Checks current Windows userID against specified userID, or against
'   predetermined access list (outlined below)
'

'===========================================================================
' Additional modules required:
'===========================================================================
'   modAppsOffice v4.05
'
'   Code included from other modules:
'      [modSpecialFolders]
'

'=========================================================================
' VERSION HISTORY
'=========================================================================
'   v2.02   bugfix: CU_Controlled opens new Excel session invisible and quits
'           (needed for compatibility with modAppsOffice v4.05)
'   v2.01   bugfix: CU_Controlled always opens new Excel session
'   v2.00   added code from modSpecialFolders
'   v1.10a  annotations only
'   v1.10   late bound references
'   v1.09   bugfix: opens lookup ReadOnly
'   v1.08   bugfixes: CU_controlled open/close
'           CheckUsers master list moved to iShare (hidden folder)
'   v1.07   bugfix: Application.Statusbar for non-Excel applications
'   v1.06   annotations improved, no functional change
'   v1.05   added CU_userID (legacy: replaces CU_tparish and CU_userKID, both remain functional)
'           renamed constants (e.g. CU_masterpth)
'   v1.02   added StatusBar messages

Option Explicit
'Checks current user KID against known access lists
' CU_userID     - checks whether current user matches specified userID  'v1.05
' CU_Public     - checks userIDs file in specified path
' CU_Controlled - checks Controlled userIDs file, here:
    Private Const CU_masterpth As String = "\\ishare.dhl.com\sites\DGFUK\BPMpublic\CheckUsers\"    'v1.08
    Private Const CU_masterfn As String = "Approved User IDs.xls"                   'v1.05
'place list of valid KIDs in column 1 of each sheet / sheet 1 of each file
'further columns and column headers are irrelevant but can be used
    Private Const CU_StatusBar = "Checking user ID"  'v1.02
    Private blnASU As Boolean


'=================================================================================================
'=================================================================================================
'=================================================================================================
'=================================================================================================

'
'   Code from modSpecialFolders module:
'

'http://answers.microsoft.com/en-us/office/forum/office_2010-customize/how-2-refer-to-desktop/97eba910-54c9-409f-9454-6d7c8d54d009
Private Declare Function SHGetSpecialFolderLocation _
                         Lib "shell32" (ByVal hwnd As Long, _
                                        ByVal nFolder As Long, ppidl As Long) As Long

Private Declare Function SHGetPathFromIDList _
                         Lib "shell32" Alias "SHGetPathFromIDListA" _
                             (ByVal Pidl As Long, ByVal pszPath As String) As Long

Private Declare Sub CoTaskMemFree Lib "ole32" (ByVal pvoid As Long)

'Desktop
Private Const CSIDL_INTERNET = &H1 'Internet Explorer (icon on desktop)
Private Const CSIDL_PROGRAMS = &H2 'Start Menu\Programs
Private Const CSIDL_CONTROLS = &H3 'My Computer\Control Panel
Private Const CSIDL_PRINTERS = &H4 'My Computer\Printers
Private Const CSIDL_PERSONAL = &H5 'My Documents
Private Const CSIDL_FAVORITES = &H6 '<user name>\Favorites
Private Const CSIDL_STARTUP = &H7 'Start Menu\Programs\Startup
Private Const CSIDL_RECENT = &H8 '<user name>\Recent
Private Const CSIDL_SENDTO = &H9 '<user name>\SendTo
Private Const CSIDL_BITBUCKET = &HA '<desktop>\Recycle Bin
Private Const CSIDL_STARTMENU = &HB '<user name>\Start Menu
Private Const CSIDL_DESKTOPDIRECTORY = &H10 '<user name>\Desktop
Private Const CSIDL_DRIVES = &H11 'My Computer
Private Const CSIDL_NETWORK = &H12 'Network Neighborhood
Private Const CSIDL_NETHOOD = &H13 '<user name>\nethood
Private Const CSIDL_FONTS = &H14 'Windows\fonts
Private Const CSIDL_TEMPLATES = &H15
Private Const CSIDL_COMMON_STARTMENU = &H16 'All Users\Start Menu
Private Const CSIDL_COMMON_PROGRAMS = &H17 'All Users\Programs
Private Const CSIDL_COMMON_STARTUP = &H18 'All Users\Startup
Private Const CSIDL_COMMON_DESKTOPDIRECTORY = &H19 'All Users\Desktop
Private Const CSIDL_APPDATA = &H1A '<user name>\Application Data
Private Const CSIDL_PRINTHOOD = &H1B '<user name>\PrintHood
Private Const CSIDL_LOCAL_APPDATA = &H1C '<user name>\Local Settings\Application Data (non roaming)
Private Const CSIDL_ALTSTARTUP = &H1D 'non localized startup
Private Const CSIDL_COMMON_ALTSTARTUP = &H1E 'non localized common startup
Private Const CSIDL_COMMON_FAVORITES = &H1F
Private Const CSIDL_INTERNET_CACHE = &H20
Private Const CSIDL_COOKIES = &H21
Private Const CSIDL_HISTORY = &H22
Private Const CSIDL_COMMON_APPDATA = &H23 'All Users\Application Data
Private Const CSIDL_WINDOWS = &H24 'Windows Directory
Private Const CSIDL_SYSTEM = &H25 'System Directory
Private Const CSIDL_PROGRAM_FILES = &H26 'C:\Program Files
Private Const CSIDL_MYPICTURES = &H27 'C:\Program Files\My Pictures
Private Const CSIDL_PROFILE = &H28 'USERPROFILE
Private Const CSIDL_SYSTEMX86 = &H29 'x86 system directory on RISC
Private Const CSIDL_PROGRAM_FILESX86 = &H2A 'x86 C:\Program Files on RISC
Private Const CSIDL_PROGRAM_FILES_COMMON = &H2B 'C:\Program Files\Common
Private Const CSIDL_PROGRAM_FILES_COMMONX86 = &H2C 'x86 Program Files\Common on RISC
Private Const CSIDL_COMMON_TEMPLATES = &H2D 'All Users\Templates
Private Const CSIDL_COMMON_DOCUMENTS = &H2E 'All Users\Documents
Private Const CSIDL_COMMON_ADMINTOOLS = &H2F 'All Users\Start Menu\Programs\Administrative Tools
Private Const CSIDL_ADMINTOOLS = &H30 '<user name>\Start Menu\Programs\Administrative Tools
Private Const CSIDL_CONNECTIONS = &H31 'Network and Dial-up Connections
Private Const MAX_PATH = 260
Private Const NOERROR = 0

Private Function SpecFolder(ByVal lngFolder As Long) As String
Dim lngPidlFound As Long
Dim lngFolderFound As Long
Dim lngPidl As Long
Dim strPath As String

strPath = Space(MAX_PATH)
lngPidlFound = SHGetSpecialFolderLocation(0, lngFolder, lngPidl)
If lngPidlFound = NOERROR Then
    lngFolderFound = SHGetPathFromIDList(lngPidl, strPath)
    If lngFolderFound Then
        SpecFolder = Left$(strPath, _
                           InStr(1, strPath, vbNullChar) - 1)
    End If
End If
CoTaskMemFree lngPidl
End Function

'=================================================================================================
'=================================================================================================
'=================================================================================================
'=================================================================================================

Private Sub CU_app(ByVal CU_Status As Boolean, Optional ByVal CU_StatusMsg As String)
'v1.07 2013-06-05 17:16
'always run  CU_app(False,CU_StatusMsg)  before and  CU_app(True)  after
'CU_StatusMsg is appended to CU_StatusBar

If CU_Status = False Then
'start of process
    If InStr(Application.Name, "Excel") > 0 Then Application.StatusBar = CU_StatusBar & CU_StatusMsg
    blnASU = Application.ScreenUpdating
    Application.ScreenUpdating = False
Else
'end of process
    Application.ScreenUpdating = blnASU
    If InStr(Application.Name, "Excel") > 0 Then Application.StatusBar = False
End If

End Sub

Function CU_userID(ByVal userID As String) As Boolean
'v2.00 2013-08-09 11:20
'checks whether current user matches specified userID

Dim CU_StatusMsg As String
CU_StatusMsg = ": user " & userID

CU_app False, CU_StatusMsg

If InStr(UCase(SpecFolder(CSIDL_PROFILE)), UCase(userID)) > 0 Then CU_userID = True

CU_app True

End Function

Function CU_Public(ByVal UserListFolder As String) As Boolean
'v1.10 2013-07-10 13:07
'checks current user KID against approved KIDs.  This function checks
'KID file [CU_masterfn] in [UserListFolder], so can be used by anyone

'list of KIDs in column 1 of CU_masterfn in UserListFolder
'further columns and column headers are irrelevant

Dim CU_StatusMsg As String
CU_StatusMsg = " against approved KIDs in " & CU_masterfn & " in " & UserListFolder

CU_app False, CU_StatusMsg

'open RecordSet from TXT, instead of opening XLS user IDs file?
Const cBsl As String = "\"
Const cFsl As String = "/"
Dim pth As String, WB As Object, rng As Object
pth = UserListFolder
If InStr(pth, cBsl) = 0 And InStr(pth, cFsl) = 0 Then
    MsgBox pth & vbLf & "Path incorrect or not specified", vbCritical, "CU_Public failed"
    Exit Function
Else
    pth = pth_sl(pth)  'adds slash to end of path if required
End If

Dim XLapp As Object
Set XLapp = XLlaunch  'requires modAppsOffice
Set WB = XLapp.Workbooks.Open(FileName:=CU_masterpth & CU_masterfn, ReadOnly:=True)
Set rng = WB.Sheets(1).Columns(1).Cells(1)
If rng.Offset(1) <> "" Then Set rng = WB.Sheets(1).Range(rng, rng.End(-4121))  'xlDown

CU_Public = CU_KIDlist(rng)

WB.Close
Set WB = Nothing

XLapp.Quit
'Set XLapp = XLclose(XLapp)
If XLapp Is Nothing Then Else MsgBox "Warn: XLclose failed"

CU_app True

End Function

Function CU_Controlled(ByVal UserList As String) As Boolean
'v2.02 2013-10-29 10:34
'checks current user KID against approved KIDs.  This function
'checks sheet [UserList] in master file on BPMpublic shared drive
'which can only be edited by specific users
'e.g. "Sales Admin" or "BPM Admin"

Dim CU_StatusMsg As String
CU_StatusMsg = " against protected KIDs in " & UserList & " sheet in " & CU_masterfn & " on BPMpublic shared drive"

CU_app False, CU_StatusMsg

If Dir(CU_masterpth & CU_masterfn) <> CU_masterfn Then Exit Function

'open RecordSet from TXT, instead of opening XLS user IDs file?
Dim XLapp As Object, WB As Object, rng As Object  'v1.10
Set XLapp = XLlaunch(False) 'v2.02 'v2.01
Set WB = XLapp.Workbooks.Open(FileName:=CU_masterpth & CU_masterfn, ReadOnly:=True)
Set rng = WB.Sheets(UserList).Columns(1).Cells(1)
If rng.Offset(1) <> "" Then Set rng = WB.Sheets(UserList).Range(rng, rng.End(-4121))  'xlDown

CU_Controlled = CU_KIDlist(rng)

WB.Close
Set WB = Nothing

If Not XLapp Is Application Then
    Set XLapp = Nothing
    If XLapp Is Nothing Then Else MsgBox "Warn: XLclose failed"
End If

CU_app True

End Function

Private Function CU_KIDlist(ByRef KIDlist As Object) As Boolean
'v1.10 2013-07-10 13:03

Dim k As Byte, kmax As Byte, userfolder As String
userfolder = UCase(SpecFolder(CSIDL_PROFILE))
kmax = KIDlist.Cells.Count
Dim userKID() As String
ReDim userKID(1 To kmax) As String
For k = 1 To kmax
    userKID(k) = UCase("" & KIDlist.Cells(k).Text)
Next k
For k = 1 To kmax
'NB: PROFILE includes \Documents and Settings\ in WinXP or \Users\ in Win7
    If InStr(userfolder, userKID(k)) > 0 Then
        CU_KIDlist = True
        Exit Function
    End If
Next k

End Function

Private Function pth_sl(ByVal PathToAddSlash As String) As String
'v1.02 2013-01-06 10:40
'from modZip v3.04 2012-11-06 16:06
'adds a slash to end of path (if required)

Const cFsl As String = "/"  'URL
Const cBsl As String = "\"  'UNC

If InStr(PathToAddSlash, cFsl) > 0 And Right(PathToAddSlash, 1) <> cFsl Then
    pth_sl = PathToAddSlash & cFsl
    Do Until InStr(cFsl & cFsl, pth_sl) = 0
        pth_sl = Replace(pth_sl, cFsl & cFsl, cFsl)
    Loop
    Exit Function
ElseIf InStr(PathToAddSlash, cBsl) > 0 And Right(PathToAddSlash, 1) <> cBsl Then
    pth_sl = PathToAddSlash & cBsl
    Do Until InStr(cBsl & cBsl, pth_sl) = 0
        pth_sl = Replace(pth_sl, cBsl & cBsl, cBsl)
    Loop
    Exit Function
End If

End Function

'**** legacy code, replaced by CU_userID in v1.05 ****
Function CU_userKID(ByVal userKID As String) As Boolean
'v1.02 2013-01-06 10:32 **** legacy code only, replaced by CU_userID in v1.05
CU_userKID = CU_userID(userKID)
End Function

'**** legacy code, replaced by CU_userID in v1.05 ****
Function CU_tparish() As Boolean
'v1.02 2013-01-06 10:32 **** legacy code only, replaced by CU_userID in v1.05
Const userKID As String = "tparish"
CU_tparish = CU_userID(userKID)
End Function