Archive for ‘MS Excel VBA Programming’

March 26th, 2013

MS Access – Bypassing the Outlook E-mail Security Warning

Yet again today, I was asked in a forum the infamous question regarding how to disable the security warning that pops up when trying to automate e-mails.  So I thought it was time to make this post on my site to help everyone that has this question.

Anyone that had the pleasure of trying to automate sending e-mails using automation (SendObject method, Outlook Automation) had the pleasure of the following security pop-up.

Microsoft Office Outlook Security Warning

So basically, Microsoft has thrown a stick in developer’s wheels in the hopes of stoping malicious software from propagating unbenounced to the user.

So the question remains, what is a developer to do to make a seamless e-mail tool? Well, as usual, there are a couple possible solutions:

Solution 1 :: Click-Yes
One option would be to download and install a piece of software such as ClickYes.  The problem with this is that it can effectively make you vulnerable to propagating malicious software… since it effectively will always authorize any access, whether the request comes from your app, or not. This also requires installation on every computer that will require sending e-mails automatically. In a controlled environment, this can be done, but for general users, this will not be a viable option.

Solution 2 :: Outlook Redemption
Another popular option is to use Outlook Redemption to send your e-mail.  The downside here is that it require registering a COM library and then recoding your e-mail automation routine.  The positive aspect here is that there are lots of examples available online!

Solution 3 :: Swicth E-mail Techniques
In my opionion, this is the easiest and best solution.  Simply stop sending e-mails through Outlook altogether.  The major downside here is that since you don’t send the e-mails through Outlook, you will not have a copy saved in your Sent Items.  The pros is that it works!  It works seamlessly!  You could switch over to CDO mailing techniques, use BLAT, use WinSock, …  Tony Toew’s covers a number of possible alternate techniques on his site http://www.granite.ab.ca/access/email.htm.

So at the end of the day, there are several solutions available to get around this problem.

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
February 27th, 2013

MS Access – VBA – Determine a Filename without the Extension

Once again, in my programming career, I have on numerous occasions needed to extract the filename from a fully qualified path/filename.extension, but just the filename without the extension. Below, is a very simple function to do so.

'---------------------------------------------------------------------------------------
' Procedure : GetFileNameWOExt
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Return the filename without the extension from a path\filename input
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' strFileWPath - string of a path and filename (ie: "c:\temp\test.xls")
'
' Returns:
' ~~~~~~~~
' test
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2012-Feb-24                 Initial Release
'---------------------------------------------------------------------------------------
Function GetFileNameWOExt(ByVal strFileWPath As String)
On Error GoTo Error_Handler
 
    GetFileNameWOExt = Right(strFileWPath, Len(strFileWPath) - InStrRev(strFileWPath, "\"))
    GetFileNameWOExt = Left(GetFileNameWOExt, InStr(GetFileNameWOExt, ".") - 1)
 
Error_Handler_Exit:
    On Error Resume Next
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
            "Error Number: " & Err.Number & vbCrLf & _
            "Error Source: GetFileNameWOExt" & vbCrLf & _
            "Error Description: " & Err.Description, _
            vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
February 26th, 2013

MS Access – VBA – Determine a File’s Extension

Another simple question, with a simple answer! At some point, you will need to extract, determine, the extension of a file. Below is a straightforward function to do so.

'---------------------------------------------------------------------------------------
' Procedure : GetFileExt
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Return the file extension from a path\filename input
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' strFileWPath - string of a path and filename (ie: "c:\temp\test.xls")
'
' Returns:
' ~~~~~~~~
' xls
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2012-Feb-24                 Initial Release
'---------------------------------------------------------------------------------------
Function GetFileExt(ByVal strFileWPath As String)
On Error GoTo Error_Handler
 
    GetFileExt = Right(strFileWPath, Len(strFileWPath) - InStrRev(strFileWPath, "."))
 
Error_Handler_Exit:
    On Error Resume Next
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
            "Error Number: " & Err.Number & vbCrLf & _
            "Error Source: GetFileExt" & vbCrLf & _
            "Error Description: " & Err.Description, _
            vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
February 19th, 2013

MS Access – VBA – Web Scrapping

I see frequently asked on various forum questions regarding pulling information off of websites. The concept is relatively straight forward, load a page, grab the content, parse what you need… You can use various need, get into textual parsing, DOM manipulation and extraction, …

There are a number of approaches that can be used, such as: Internet Explorer automation, MSXML2.XMLHTTP, …

As usual, the information on how to do this is sparse, and sometimes hard to find, especially when you don’t even know the proper terms to search for in the first place. Below are a few links to help you get on your way.

http://www.jpsoftwaretech.com/an-exploration-of-ie-browser-methods-part-i/
http://www.jpsoftwaretech.com/an-exploration-of-ie-browser-methods-part-ii/
http://www.jpsoftwaretech.com/an-exploration-of-ie-browser-methods-part-iii/
http://www.jpsoftwaretech.com/vba/msxml-object-library-routines/
http://www.jpsoftwaretech.com/website-parsingretrieval-using-xml/
http://www.accessmvp.com/djsteele/smartaccess.html – Scroll down to the bottom and look at the article entitled: “April 2006: Surfs up!”

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
January 22nd, 2013

Excel – VBA – Delete All Data Validation

Have you tried to publish as a web app an Excel Workbook and received an error regarding Data Validation (as shown in the image below) stating “The workbook cannot be opened because it contains the following features that are not supported by Excel in the browser. Data Validation. …”.

[begin rant]Isn’t it great that MS has made its own feature incompatible with its own software! Brilliant (again)! What is even better is they do not provide a tools to convert, render a file compatible.[/end rant]

 

DataValidationIncompatibilityError

 

Now the only source of help I could locate was an explanation that you could use the find utility to locate cells with data validation and the delete them one by one…. For a simple workbook, maybe and even then. But when you are working with 10s, 100s of worksheets with 100s, 1000s or rows/column it simply become unfeasible to even consider doing this manually. As such, I put together the following routine to clean out any existing Data Validation from a workbook. This is a brute force method, but it does work.

 

'---------------------------------------------------------------------------------------
' Procedure : ClearAllDataValidation
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Remove all data validation from a workbook
'             To make it compatible with SharePoint
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2013-Jan-22                 Initial Release
'---------------------------------------------------------------------------------------
Function ClearAllDataValidation()
    'On Error GoTo Error_Handler
    Dim ws              As Worksheet
 
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
 
    For Each ws In Worksheets
        Debug.Print "Processing worksheet :: " & ws.Name
        wsVisible = ws.visible    'Original visibility setting
        ws.visible = xlSheetVisible    'Make the worksheet visible
        ws.Activate
        For Each Cell In ActiveSheet.UsedRange.Cells
            On Error Resume Next
            If Cell.SpecialCells(xlCellTypeSameValidation).Cells.Count < 1 Then
                'No validation
            Else
                Cell.Validation.Delete
            End If
            On Error GoTo 0
        Next
        ws.visible = wsVisible    'set it back as it was originally
    Next ws
 
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
 
Error_Handler_Exit:
    On Error Resume Next
    Debug.Print "Done!"
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: ClearAllDataValidation" & vbCrLf & _
           "Error Description: " & Err.Description, _
           vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

I would like to refine it further, but well see. Since this is the type of thing you only need to do once, optimizing it further isn’t a priority right now. Time permitting down the road. Off to put out the next fire for now.

Also, if you are looking for a listing of what is and isn’t compatible between regular MS Excel workbooks and those open using a web-based browser, see: http://office.microsoft.com/en-us/sharepoint-server-help/differences-between-using-a-workbook-in-the-browser-and-in-excel-HA010369179.aspx. There you’ll see a listing of what is compatible, what isn’t and what might behave differently. For instance, workbooks with VBA will have the VBA non-functional and the file itself will not be editable!

So at the end of the day, using Excel files through a web-browser will only work for the most basic workbook! Be forewarned.

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
October 25th, 2012

MS Excel – VBA – Number of Used Columns in WorkSheets

Sometimes you need to loop through all the columns within a given worksheet, so you need to first ascertain what is the last column in the worksheet. So how can one do this reliably?

Well, if all you columns are visible, then you can use code such as:

Dim iLastCol        As Long
iLastCol = Sheets("YourSheetName").Cells(7, Sheets("YourSheetName").Columns.Count).End(xlToLeft).Column

Or

Dim iLastCol        As Long
iLastCol = ActiveSheet.Cells(7, ActiveSheet.Columns.Count).End(xlToLeft).Column

Now that is all fine and dandy, if all your columns are visible, but what happens when you need to identify the last column even if those column may or may not be visible? Once again, no major problem. We just need to tweak our code to something like:

Dim iLastCol        As Long
iLastCol = Sheets("YourSheetName").UsedRange.Columns(Sheets("YourSheetName").UsedRange.Columns.Count).Column

Or

Dim iLastCol        As Long
iLastCol = ActiveSheet.UsedRange.Columns(ActiveSheet.UsedRange.Columns.Count).Column

Now both can be very useful in different situations. Just beware that there is a difference depending on whether or not you want to include hidden columns in your count/loop.

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
October 25th, 2012

MS Excel – VBA – Hide all WorkSheets

In the same thought process as my previous post MS Excel – VBA – Unhide as WorkSheets in a WorkBook, below is are two simply procedures. The first will hide all the WorkSheets within the WorkBook, however they can still be made visible by the user through the standard Excel menus. The second one, hides all the WorkSheets but this time they are ‘veryhidden’, which means there is no way for the user to unhide them without using VBA to do so. Even if they use the standard menus the ‘very hidden’ sheets will not appear.

'---------------------------------------------------------------------------------------
' Procedure : hideAllWs
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Hide all the worksheets except for the active sheet
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).

' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2012-Oct-25                 Initial Release
'---------------------------------------------------------------------------------------
Function hideAllWs()
On Error GoTo Error_Handler
    Dim WS              As Worksheet
 
    For Each WS In Worksheets
        If WS.Name <> ActiveSheet.Name Then WS.visible = xlSheetHidden
    Next WS
 
Error_Handler_Exit:
    On Error Resume Next
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
            "Error Number: " & Err.Number & vbCrLf & _
            "Error Source: hideAllWs" & vbCrLf & _
            "Error Description: " & Err.Description, _
            vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function
'---------------------------------------------------------------------------------------
' Procedure : VeryhideAllWs
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Hide all the worksheets except for the active sheet
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).

' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2012-Oct-25                 Initial Release
'---------------------------------------------------------------------------------------
Function VeryhideAllWs()
On Error GoTo Error_Handler
    Dim WS              As Worksheet
 
    For Each WS In Worksheets
        If WS.Name <> ActiveSheet.Name Then WS.visible = xlSheetVeryHidden
    Next WS
 
Error_Handler_Exit:
    On Error Resume Next
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
            "Error Number: " & Err.Number & vbCrLf & _
            "Error Source: VeryhideAllWs" & vbCrLf & _
            "Error Description: " & Err.Description, _
            vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

You’ll notice in both routines that it will not hide the active worksheet. That is because you can’t, it will err. So you need to set focus on whatever worksheet you want to remain visible and then run it to hide all the other sheets in the workbook.

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
October 25th, 2012

MS Excel – VBA – Unhide All WorkSheets in a WorkBook

I created a monster. Well sort of. I created a security routine that controls the visibility of worksheet based on the current user. This is great, but as the developer and tester, impersonating other users, I didn’t want to have to make 70+ Worksheets visible again. Even more so since, I was using the xlSheetVeryHidden visibility property making it impossible to restore manually! So what to do. Easy, create a very simple routine to loop through all the WorkSheets of the current WorkBook and set them all visible again.

'---------------------------------------------------------------------------------------
' Procedure : UnhideAllWs
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Loop through all the WorkSheets of the current WorkBook and set them all
'             to visible.
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).

' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2012-Oct-25                 Initial Release
'---------------------------------------------------------------------------------------
Function UnhideAllWs()
On Error GoTo Error_Handler
    Dim WS              As Worksheet
 
    For Each WS In Worksheets
        WS.visible = xlSheetVisible
    Next WS
 
Error_Handler_Exit:
    On Error Resume Next
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
            "Error Number: " & Err.Number & vbCrLf  _
            "Error Source: UnhideAllWs" & vbCrLf & _
            "Error Description: " & Err.Description, _
            vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
July 13th, 2012

VBA – List of files in a specified Folder or Directory

Ever needed to extract a list of files within a folder/directory? Ever needed to iterate through the files within a given folder/ directory? Below is a simple illustration of how you can do it using the Dir() function. Many examples commonly utilize the FileSystem object, when in reality there is no need to use an external library to do this simple task! As they say Keep It Simple Stupid (the KISS philosophy).

'---------------------------------------------------------------------------------------
' Procedure : fListDirFiles
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Return a list of files in a given directory
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sPath     : Full path of folder to examine with trailing \
' sFilter   : specific file extension to limmit search to, leave blank to list all files
'
' Usage:
' ~~~~~~
' fListDirFiles("C:\Users\Daniel\Documents\") 'List all the files
' fListDirFiles("C:\Users\Daniel\Documents\","xls") 'Only list Excel files
' fListDirFiles("C:\Users\Daniel\Documents\","doc") 'Only list Word files
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2012-Jul-13             Initial Release
'---------------------------------------------------------------------------------------
Function fListDirFiles(sPath As String, Optional sFilter As String = "*")
On Error GoTo Error_Handler
    Dim sFile As String
 
    sFile = Dir(sPath & "*." & sFilter)
        Do While sFile <> vbNullString
            If sFile <> "." And sFile <> ".." Then
                    Debug.Print sFile & " was found"
                    'Do something with the found file
            End If
            sFile = Dir 'Loop through the next file that was found
        Loop
 
Error_Handler_Exit:
    On Error Resume Next
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
            "Error Number: " & Err.Number & vbCrLf & _
            "Error Source: fListDirFiles" & vbCrLf & _
            "Error Description: " & Err.Description, _
            vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
July 7th, 2012

VBA – Export to Text File

Below is a similar function to my AppendTxt function, expect this one overwrites any existing data in the destination text file instead of appending it like in the AppendTxt function.

'---------------------------------------------------------------------------------------
' Procedure : OverwriteTxt
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Output Data to an external file (*.txt or other format)
'             ***Do not forget about access' DoCmd.OutputTo Method for
'             exporting objects (queries, report,...)***
'             Will overwirte any data if the file already exists
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFile - name of the file that the text is to be output to including the full path
' sText - text to be output to the file
'
' Usage:
' ~~~~~~
' Call OverwriteTxt("C:\Users\Vance\Documents\EmailExp2.txt", "Text2Export")
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2012-Jul-06                 Initial Release
'---------------------------------------------------------------------------------------
Function OverwriteTxt(sFile As String, sText As String)
On Error GoTo Err_Handler
    Dim FileNumber As Integer
 
    FileNumber = FreeFile                   ' Get unused file number
    Open sFile For Output As #FileNumber    ' Connect to the file
    Print #FileNumber, sText                ' Append our string
    Close #FileNumber                       ' Close the file

Exit_Err_Handler:
    Exit Function
 
Err_Handler:
    MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: OverwriteTxt" & vbCrLf & _
           "Error Description: " & Err.Description, vbCritical, "An Error has Occured!"
    GoTo Exit_Err_Handler
End Function

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
July 6th, 2012

VBA – Count files in Folder/Directory

Below is a simple function that will return the count (number) of files contained within a supplied folder path.

'---------------------------------------------------------------------------------------
' Procedure : FlrFileCount
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Return a count of the number of files in a specified folder/directory
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFileFlr  : Full path of the folder to count the number files within
'
' Usage:
' ~~~~~~
' FlrFileCount("C:\Users\Esther\Documents\cdo")  ::  Will return a numeric value
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2010-Jan-11             Initial Release
'---------------------------------------------------------------------------------------
Function FlrFileCount(sFileFlr As String) As Long
On Error GoTo Error_Handler
    Dim fso As Object
    Dim flr As Object
 
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set flr = fso.GetFolder(sFileFlr)
 
    FlrFileCount = flr.Files.Count
 
Error_Handler_Exit:
    On Error Resume Next
    Set flr = Nothing
    Set fso = Nothing
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
            "Error Number: " & Err.Number & vbCrLf & _
            "Error Source: FlrFileCount" & vbCrLf & _
            "Error Description: " & Err.Description, _
            vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
June 22nd, 2012

VBA – Determine the state of a file, Is a file already open

Ever needed to determine if an Excel Workbook was already open, perhaps a Word document. The little function below can help you determine the state of a file.

'---------------------------------------------------------------------------------------
' Procedure : fGetFileState
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Determine the current state of a given file
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFile     - Full path and filename with extension to determine the state of
'
' Usage:
' ~~~~~~
' fGetFileState("C:\Databases\testme.xlsm")
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2009-Oct-09             Initial Release
'---------------------------------------------------------------------------------------
Function fGetFileState(sFile As String) As String
    On Error GoTo Error_Handler
    Dim iFileNo         As Integer
 
    iFileNo = FreeFile
    Open sFile For Input Lock Read As iFileNo
    Close iFileNo
 
Error_Handler_Exit:
    On Error Resume Next
    If fGetFileState = vbNullString Then fGetFileState = "File is not open"
    Exit Function
 
Error_Handler:
    Select Case Err.Number
        Case 53
            fGetFileState = "File does not exist"
        Case 70
            fGetFileState = "Permission denied - File is already open"
        Case 76
            fGetFileState = "Path not found"
        Case Else
            fGetFileState = "Unknow State"
    End Select
    GoTo Error_Handler_Exit
End Function

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
May 14th, 2012

VBA – Read File into Memory

The following function enable you to read in, for instance a text file, into memory to use within your routines.

'---------------------------------------------------------------------------------------
' Procedure : ReadFile
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Faster way to read text file all in RAM rather than line by line
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
' Input Variables:
' ~~~~~~~~~~~~~~~~
' strFile - name of the file that is to be read
'
' Usage Example:
' ~~~~~~~~~~~~~~~~
' MyTxt = ReadText("c:\tmp\test.txt")
' MyTxt = ReadText("c:\tmp\test.sql")
' MyTxt = ReadText("c:\tmp\test.csv")
'---------------------------------------------------------------------------------------
Function ReadFile(ByVal strFile As String) As String
On Error GoTo Error_Handler
    Dim FileNumber  As Integer
    Dim sFile       As String 'Variable contain file content

    'If FileExist(strFile) = False Then
    '    MsgBox "The specified file could not be found!"
    '    Exit Function
    'End If
    
    FileNumber = FreeFile
    Open strFile For Binary Access Read As FileNumber
    sFile = Space(LOF(FileNumber))
    Get #FileNumber, , sFile
    Close FileNumber
 
    ReadFile = sFile
 
Error_Handler_Exit:
    On Error Resume Next
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
            "Error Number: " & Err.Number & vbCrLf & _
            "Error Source: ReadFile" & vbCrLf & _
            "Error Description: " & Err.Description, _
            vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

c

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
May 14th, 2012

MS Access – VBA – Convert Excel XLS to CSV

I was asked in a support forum how to convert an Excel *.xls, *.xlsx file to *.csv format. I didn’t readily have an answer so I created a custom function to help the user out. So here are the fruits on my labors should it help someone else out. What is also nice about the way it is written, is that it will run in any MS Office application (MS Access, MS Word, MS PowerPoint, MS Outlook, …) without requiring any modifications (copy & paste, that’s it)!

'---------------------------------------------------------------------------------------
' Procedure : ConvertXls2CSV
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Converts a standard Excel file to csv format
' Requirements: Requires MS Excel be installed
'               Uses late binding, so no libraries need be declared
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sXlsFile  : Fully qualified path and filename with extension of the Excel workbook
'
' Usage:
' ~~~~~~
' ConvertXls2CSV "C:\Users\Daniel\Desktop\Contact_E-mail listing.xls"
'       Will output a file C:\Users\Daniel\Desktop\Contact_E-mail listing.csv
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2012-May-11             Initial Release - Answer to forum question
'---------------------------------------------------------------------------------------
Function ConvertXls2CSV(sXlsFile As String)
    On Error Resume Next
    Dim oExcel          As Object
    Dim oExcelWrkBk     As Object
    Dim bExcelOpened    As Boolean    'Was Excel already open or not
    'Review 'XlFileFormat Enumeration' for more formats
    Const xlCSVWindows = 23 'Windows CSV Format
    Const xlCSV = 6 'CSV
    Const xlCSVMac = 22 'Macintosh CSV
    Const xlCSVMSDOS = 24 'MSDOS CSV

    Set oExcel = GetObject(, "Excel.Application")    'Bind to existing instance of Excel

    If Err.Number <> 0 Then    'Could not get instance of Excel, so create a new one
        Err.Clear
        On Error GoTo Error_Handler
        Set oExcel = CreateObject("excel.application")
        bExcelOpened = False
    Else    'Excel was already running
        bExcelOpened = True
    End If
 
    On Error GoTo Error_Handler
    oExcel.ScreenUpdating = False
    oExcel.Visible = False   'Keep Excel hidden from the user
    oExcel.Application.DisplayAlerts = False
 
    Set oExcelWrkBk = oExcel.Workbooks.Open(sXlsFile)
    'Note: you may wish to change the file format constant for another type declared
    '      above based on your usage/needs in the following line.
    oExcelWrkBk.SaveAs Left(sXlsFile, InStrRev(sXlsFile, ".")) & "csv", xlCSVWindows
    oExcelWrkBk.Close False
 
    If bExcelOpened = False Then
        oExcel.Quit
    End If
 
Error_Handler_Exit:
    On Error Resume Next
    Set oExcelWrkBk = Nothing
    Set oExcel = Nothing
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
            "Error Number: " & Err.Number & vbCrLf & _
            "Error Source: ConvertXls2CSV" & vbCrLf & _
            "Error Description: " & Err.Description, _
            vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

Now this could be further improved by extending the error handling further to trap specific errors such as 1004 – file not found, etc… but it definitely illustrates the basic principle in using late binding to utilize Excel to open the file and convert it to *.csv format.

I hope this helps.

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
March 3rd, 2012

MS Access – VBA – Capitalize the First Letter of a String

Below is an example of a function which will capitalize the first letter of a given string.  The second input variable allows you to specify to return the rest of the string as is, or lowercase it.

'---------------------------------------------------------------------------------------
' Procedure : UCase1stLtr
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Capitalize the first character of a given string
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sString           String to process
' bLowerCaseTheRest Whether or not the rest of the string should be in lower case or not
'
' Usage:
' ~~~~~~
' UCase1stLtr("hjkwhjkwhkjw12218hjksdjkhNJH", False) -&gt; Hjkwhjkwhkjw12218hjksdjkhNJH
' UCase1stLtr("hjkwhjkwhkjw12218hjksdjkhNJH", True) -&gt; Hjkwhjkwhkjw12218hjksdjkhnjh
' UCase1stLtr("hjkwhjkwhkjw12218hjksdjkhNJH") -&gt; Hjkwhjkwhkjw12218hjksdjkhnjh
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2012-Mar-02                 Initial Release
'---------------------------------------------------------------------------------------
Function UCase1stLtr(sString As String, Optional bLowerCaseTheRest As Boolean = True) As String
On Error GoTo Error_Handler
 
    Select Case Len(sString)
        Case 0
            UCase1stLtr = vbNullString
        Case 1
            UCase1stLtr = UCase(sString)
        Case Else
            UCase1stLtr = UCase(Left(sString, 1)) &amp; IIf(bLowerCaseTheRest, LCase(Mid(sString, 2)), Mid(sString, 2))
    End Select
 
Error_Handler_Exit:
    On Error Resume Next
    Exit Function
 
Error_Handler:
    MsgBox Err.Number &amp; vbCrLf &amp; Err.Description &amp; vbCrLf &amp; sModName &amp; "/UCase1stLtr", True
    Resume Error_Handler_Exit
End Function

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
February 2nd, 2012

VBA – Directory/Folder Name Validation

I had a need to create folders from Access, but needed a means to first validate that the folders names were acceptable as Windows does not allow certain characters and has certain basic rules (refer to the 2 links commented out in the function below for all the details).  As such, I created the following simple function which I supply the folder name to and it returns True/False whether the string is acceptable or not.  It really wasn’t very difficult and this is the perfect situation in which to utilize the power of regular expression to validate the folder name with!

'---------------------------------------------------------------------------------------
' Procedure : IsInvalidFolderName
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Validates whether the string passed is an acceptable folder name
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFolderName name of the folder you're wanting to create
'
' Usage:
' ~~~~~~
' IsValidFolderName("MsAccess Databases") will return True
' IsValidFolderName("MsAccess :: Databases") will return False
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2012-Feb-01                 Initial Release
'---------------------------------------------------------------------------------------
Function IsValidFolderName(ByVal sFolderName As String) As Boolean
'http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#file_and_directory_names
'http://msdn.microsoft.com/en-us/library/ie/ms974570.aspx
    On Error GoTo Error_Handler
    Dim oRegEx          As Object
 
    'Check to see if any illegal characters have been used
    Set oRegEx = CreateObject("vbscript.regexp")
    oRegEx.Pattern = "[&lt;&gt;:""/\\\|\?\*]"
    IsValidFolderName = Not oRegEx.test(sFolderName)
    'Ensure the folder name does end with a . or a blank space
    If Right(sFolderName, 1) = "." Then IsValidFolderName = False
    If Right(sFolderName, 1) = " " Then IsValidFolderName = False
 
Error_Handler_Exit:
    On Error Resume Next
    Set oRegEx = Nothing
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occurred" &amp; vbCrLf &amp; vbCrLf &amp; _
           "Error Number: " &amp; Err.Number &amp; vbCrLf &amp; vbCrLf &amp; _
           "Error Source: IsInvalidFolderName" &amp; vbCrLf &amp; _
           "Error Description: " &amp; Err.Description, _
           vbCritical, "An Error has Occurred!"
    Resume Error_Handler_Exit
End Function

Enjoy!

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
December 8th, 2011

MS Excel-VBA-Reset AutoFilter

I needed to ensure that no AutoFilters were set before running some other procedures. Below is a very simple sub routine that you can use do reset any, and all, AutoFilters within an Excel Workbook.

'---------------------------------------------------------------------------------------
' Procedure : ResetAutoFilters
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Resets all the AutoFilter in all the worksheets of the current workbook
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2011-December-07        Initial Release
'---------------------------------------------------------------------------------------
Sub ResetAutoFilters()
On Error GoTo Error_Handler
    Dim w As Worksheet
 
    For Each w In Worksheets
        If w.FilterMode Then w.ShowAllData
    Next w
 
Exit_Error_Handler:
    Exit Sub
 
Error_Handler:
    MsgBox "Error Number: " & Err.Number & vbCrLf & _
           "Error Description: " & Err.Description & vbCrLf & _
           "Error Source: " & "ResetAutoFilters", vbCritical, "An Error Has Occured"
    Resume Exit_Error_Handler
End Sub

Similarily, if you wanted to reset the AutoFilter in one specific worksheet to display all the data, you could use a procedure such as:

'---------------------------------------------------------------------------------------
' Procedure : ResetAutoFilter
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Reset the AutoFilter in the specified worksheet of the active workbook
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' w - Worksheet
'
' Usage:
' ~~~~~~
' ResetAutoFilter sheets("Sheet1") ~ resets a specific sheet named Sheet1
' ResetAutoFilter sheets(6) ~ resets the 6th sheet in the workbook
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2011-Dec-07                 Initial Release
'---------------------------------------------------------------------------------------
Sub ResetAutoFilter(w As Worksheet)
On Error GoTo Error_Handler
 
        If w.FilterMode Then w.ShowAllData
 
Exit_Error_Handler:
    Exit Sub
 
Error_Handler:
    MsgBox "Error Number: " & Err.Number & vbCrLf & _
           "Error Description: " & Err.Description & vbCrLf & _
           "Error Source: "ResetAutoFilter", vbCritical, "An Error Has Occured"
    Resume Exit_Error_Handler
End Sub

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
November 15th, 2011

MS Excel – VBA – Print 1 Page Wide

Have you ever wanted to setup your spreadsheet to print 1 page wide? It sounds like such a simple thing to do, and yet at first glance it appears not to be so easy in Excel’s VBA.

Now if you record a macro, or do some searching online, you’ll find that the method for setting up such settings using code, such as:

With ActiveSheet.PageSetup
    .FitToPagesWide = 1
    .FitToPagesTall = 5
End With

The problem being that you need to specify how many pages tall the document will be. Now I came across numerous post where people try to determine insert page breaks based on number of rows, or insert page breaks based on the height of rows, or I also came across posting stating to set the .FitToPagesTall to a extremely large number and Excel will automatically fit is properly.

Now, yes, these solutions will work, some requiring a lot more work than others, but as I found out, there is no need for such conveluted methods. One can merely set the .FotToPagesTall to False and Excel will resize according to fit the content by whatever value you specified in the .FitToPagesWide. So the finally code would merely be:

With ActiveSheet.PageSetup
    .FitToPagesWide = 1
    .FitToPagesTall = False 'Will take as many pages as required based on other settings
End With

Inversly, you could specify the .FitToPagesWide and set the value of .FitToPagesTall to False and Excel will resize accordingly.

One more simple technique in your bag of tricks!

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
September 16th, 2011

VBA – Determine if a Folder/Directory Exists or Not

It can often come handy to be able to quick determine if a Folder/Directory exists or not. Below is a function I created some time ago to do exactly that.

'---------------------------------------------------------------------------------------
' Procedure : FolderExist
' DateTime  : 2009-Oct-02 13:51
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Test for the existance of a Folder/Directory
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFolder - Full path of the folder to be tested for
'---------------------------------------------------------------------------------------
Function FolderExist(sFolder As String) As Boolean
On Error GoTo Error_Handler
 
    If sFolder = vbNullString Then GoTo Error_Handler_Exit
    If Dir(sFolder, vbDirectory) <> vbNullString Then
        FolderExist = True
    End If
 
Error_Handler_Exit:
    On Error Resume Next
    Exit Function
 
Error_Handler:
    If Err.Number <> 52 Then
        MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: FolderExist" & vbCrLf & _
           "Error Description: " & Err.Description, vbCritical, "An Error has Occured"
    End If
    Resume Error_Handler_Exit
End Function

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
September 15th, 2011

VBA – Create Directory Structure/Create Multiple Directories/Create Nested Directories

One of he most common methods for creating directories/folders in VBA is to use the MkDir statement. For instance:

MkDir "C:\databases\"

One quickly learns the limitations of this technique the minute they have to create a directory structure with multiple sub-folders. MkDir can only create 1 directory at a time and cannot create a sub-directory. Hence, assuming that C:\databases does not already exist, the following would not work and will return an error!

MkDir "C:\databases\msaccess\"

If you absolutely want to create such a structure using the MkDir statement you’d have to do so using 2 MkDir statement. For instance:

MkDir "C:\databases\"
MkDir "C:\databases\msaccess\"

Now if you need to merely create 1 or 2 sub-folder MkDir may still be acceptable, but there are cases where this is simply impracticle and another solution needs to be found. Well, I found two possible solutions!

One possible approach can be found at Creating Nested Directories.

The second I found searching through the net and I no longer know the original source of the code (if someone knows e-mail me and I will put credit where it is due). It is a simple API which can create multiple directories in 1 call.

Private Declare Function MakeSureDirectoryPathExists Lib "imagehlp.dll" (ByVal lpPath As String) As Long
 
Public Sub MakeFullDir(strPath As String)
    If Right(strPath, 1) <> "\" Then strPath = strPath & "\" 'Optional depending upon intent
    MakeSureDirectoryPathExists strPath
End Sub

Another possible solution, if someone wanted to tinker a little would be to merely parse the path into it’s directories and the using the DIR statement evaluate and create the directories where need be. Shouldn’t be that hard, but I haven’t taken the time to do this (maybe one day I will and will update this post then).

Okay, so it bothered me and I had to quickly put something together to stop my brain from churning! Below is what I pieced together rapidly. It is missing proper variable definitions (DIM statements) and error handling, but from my very brief testing, it does appear to work and doesn’t require any APIs! 100% VBA.

Public Sub MyMkDir(sPath As String)
    Dim iStart          As Integer
    Dim aDirs           As Variant
    Dim sCurDir         As String
    Dim i               As Integer
 
    If sPath <> "" Then
        aDirs = Split(sPath, "\")
        If Left(sPath, 2) = "\\" Then
            iStart = 3
        Else
            iStart = 1
        End If
 
        sCurDir = Left(sPath, InStr(iStart, sPath, "\"))
 
        For i = iStart To UBound(aDirs)
            sCurDir = sCurDir & aDirs(i) & "\"
            If Dir(sCurDir, vbDirectory) = vbNullString Then
                MkDir sCurDir
            End If
        Next i
    End If
End Sub

As you can see, there are numerous way to handles this issue. Hopefully this helped answer a question for a few of you out there!

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
June 22nd, 2011

VBA – List Application Command Bars

I ran into a particular problem with an associate of mine not too long ago and thaught I’d share the problem & solution with everyone. He had been given an .accdb database that evidently came from an mdb originally as it contained a custom command bar. The problem being that 2007/2010 support such command bars by simply placing them in the Add-Ins tab. However, this issue lies with the fact that 2007/2010 no longer offer the general user/developer a method to edit such command bars as they are considered to be deprecated. My associate wanted to merely delete this command bar and replace it with a proper custom Ribbon Tab. So how do you delete a command bar? Good question! In 2007/2010 the only solution is to use VBA. The actual code to delete a command bar is very simple, as shown below.

Application.CommandBars("CommandBarName").Delete

Sound simple you say. Sadly, no! Once again because MS has decided no longer provide any tools to work with these ‘elements’, you cannot identify the name of the Add-Ins toolbars. if you can’t identify it, you can’t delete it! So what to do? Well, I came up with another simple solution and created a procedure that merely listed all the command bars within the current database. then we could go through the list and identify the one that we needed to delete. Below are two slightly different procedures. The first one is a more general version which merely lists all of the command bars within the database, the second is a slightly more refined version that only lists open command bars. Since the Add-Ins Tab was active, the 2nd procedure was a better option in our case and thus reduce the list we had to sift through (our list went from 202 items to 4 – from there it was easy to determine which one we needed to eliminate).

'---------------------------------------------------------------------------------------
' Procedure : ListCmdBars
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Lists all the command bars within the current database
' Compatibility: Works with MS Access, Word, Excel, PowerPoint, ...
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2011-June-22            Initial Release
'---------------------------------------------------------------------------------------
Function ListCmdBars()
On Error GoTo Error_Handler
    Dim i           As Long
    Dim sCmdBar     As CommandBar
 
    Debug.Print "Number", "Name", "Visible", "Built-in"
    For i = 1 To Application.CommandBars.Count
        Set sCmdBar = Application.CommandBars(i)
        Debug.Print i, sCmdBar.Name, sCmdBar.Visible, sCmdBar.BuiltIn
    Next i
Error_Handler_Exit:
    On Error Resume Next
    Set sCmdBar = Nothing
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: ListCmdBars" & vbCrLf & _
           "Error Description: " & Err.Description, vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

'---------------------------------------------------------------------------------------
' Procedure : ListVisibleCmdBars
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Lists all the visible command bars within the current database
' Compatibility: Works with MS Access, Word, Excel, PowerPoint, ...
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2011-June-22            Initial Release
'---------------------------------------------------------------------------------------
Function ListVisibleCmdBars()
On Error GoTo Error_Handler
    Dim i           As Long
    Dim j           As Long
    Dim sCmdBar     As CommandBar
 
    Debug.Print "Number", "Name", "Visible", "Built-in"
    For i = 1 To Application.CommandBars.Count
        Set sCmdBar = Application.CommandBars(i)
        If sCmdBar.Visible = True Then
            j = j + 1
            Debug.Print j, sCmdBar.Name, sCmdBar.Visible, sCmdBar.BuiltIn
        End If
    Next i
Error_Handler_Exit:
    On Error Resume Next
    Set sCmdBar = Nothing
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: ListVisibleCmdBars" & vbCrLf & _
           "Error Description: " & Err.Description, vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

So as you can see, it is still possible to manipulate command bars in MS Access 2007/2010, but it can now only be done through the use of VBA code!

Thanks to a post by Albert Kallal, a fellow MVP, we also found out that it could be necessary to execute the following

CurrentDb.Properties.Delete("StartUpMenuBar")

and in our case it was required as even after deleting the commandbar in question we were still receiving the error message

… can’t find the object ‘MyCommandBarName.’
If ‘MyCommandBarName’ is a new macro or macro group, make sure you have saved it and that you have type its name correctly

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
June 8th, 2011

VBA – Extract the File Name from a Complete File Path and Name

You can use the following procedure to extract the path from a full file name. You supply the file address, complete file path and file name (ie: “C:\Documents and Settings\User\Desktop\Details.txt”) and it will return the file name (ie: “Details.txt”)

'---------------------------------------------------------------------------------------
' Procedure : GetFileName
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Return the filename from a path\filename input
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFile - string of a path and filename (ie: "c:\temp\test.xls")
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2008-Feb-06                 Initial Release
'---------------------------------------------------------------------------------------
Function GetFileName(sFile As String)
On Error GoTo Err_Handler
 
    GetFileName = Right(sFile, Len(sFile) - InStrRev(sFile, "\"))
 
Exit_Err_Handler:
    Exit Function
 
Err_Handler:
    MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: GetFileName" & vbCrLf & _
           "Error Description: " & Err.Description, vbCritical, "An Error has Occured!"
    GoTo Exit_Err_Handler
End Function

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
June 7th, 2011

VBA – Extract the Path from a Complete File Path and Name

You can use the following procedure to extract the path from a full file name. You supply the file address, complete file path and file name (ie: “C:\Documents and Settings\User\Desktop\Details.txt”) and it will return the path (ie: “C:\Documents and Settings\User\Desktop\”)

'---------------------------------------------------------------------------------------
' Procedure : GetFilePath
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Return the path from a path\filename input
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFile - string of a path and filename (ie: "c:\temp\test.xls")
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2008-Feb-06                 Initial Release
'---------------------------------------------------------------------------------------
Function GetFilePath(sFile As String)
On Error GoTo Err_Handler
 
    GetFilePath = Left(sFile, InStrRev(sFile, "\"))
 
Exit_Err_Handler:
    Exit Function
 
Err_Handler:
    MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: GetFilePath" & vbCrLf & _
           "Error Description: " & Err.Description, vbCritical, "An Error has Occured!"
    GoTo Exit_Err_Handler
End Function

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
June 6th, 2011

VBA – Append Text to a Text File

Ever simply wanted to append data into an existing text file? The procedure below does exactly that. Simply supply the full path and file name of the text file to append to, and supply the string to append and voila!

'---------------------------------------------------------------------------------------
' Procedure : AppendTxt
' DateTime  : 2007-Mar-06 10:14
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Output Data to an external file (*.txt or other format)
'             ***Do not forget about access' DoCmd.OutputTo Method for
'             exporting objects (queries, report,...)***
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFile - name of the file that the text is to be output to including the full path
' sText - text to be output to the file
'---------------------------------------------------------------------------------------
Function AppendTxt(sFile As String, sText As String)
On Error GoTo Err_Handler
    Dim FileNumber As Integer
 
    FileNumber = FreeFile                   ' Get unused file number
    Open sFile For Append As #FileNumber    ' Connect to the file
    Print #FileNumber, sText                ' Append our string
    Close #FileNumber                       ' Close the file

Exit_Err_Handler:
    Exit Function
 
Err_Handler:
    MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: AppendTxt" & vbCrLf & _
           "Error Description: " & Err.Description, vbCritical, "An Error has Occured!"
    GoTo Exit_Err_Handler
End Function

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print
June 5th, 2011

VBA – Determine if a File Exists or Not

Here is another simple procedure that allows one to verify/check if a file exists or not.

'---------------------------------------------------------------------------------------
' Procedure : FileExist
' DateTime  : 2007-Mar-06 13:51
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Test for the existance of a file; Returns True/False
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' strFile - name of the file to be tested for including full path
'---------------------------------------------------------------------------------------
Function FileExist(strFile As String) As Boolean
On Error GoTo Err_Handler
 
    FileExist = False
    If Len(Dir(strFile)) > 0 Then
        FileExist = True
    End If
 
Exit_Err_Handler:
    Exit Function
 
Err_Handler:
    MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: FileExist" & vbCrLf & _
           "Error Description: " & Err.Description, vbCritical, "An Error has Occured!"
    GoTo Exit_Err_Handler
End Function

Share and Enjoy

  • Google Plus
  • Facebook
  • LinkedIn
  • Twitter
  • Email
  • Print