Archive for September, 2010

September 29th, 2010

MS Access – VBA – Copy a File

Have you ever needed to make a copy of a file? Well, there are a number of ways that you can do it. For instance, one could create a FileScripting instance, but I find that using the FileCopy function to be the simplest and cleaness method. I created a very simply procedure around it to trap certain common errors.

'---------------------------------------------------------------------------------------
' Procedure : CopyFile
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Copy a file
'             Overwrites existing copy without prompting
'             Cannot copy locked files (currently in use)
' 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:
' ~~~~~~~~~~~~~~~~
' strSource - Path/Name of the file to be copied
' strDest - Path/Name for copying the file to
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
' 1         2007-Apr-01             Initial Release
'---------------------------------------------------------------------------------------
Function CopyFile(strSource As String, strDest As String) As Boolean
On Error GoTo CopyFile_Error
 
    FileCopy strSource, strDest
    CopyFile = True
    Exit Function
 
CopyFile_Error:
    If Err.Number = 0 Then
    ElseIf Err.Number = 70 Then
        MsgBox "The file is currently in use and therfore is locked and cannot be copied at this" & _
               " time.  Please ensure that no one is using the file and try again.", vbOKOnly, _
               "File Currently in Use"
    ElseIf Err.Number = 53 Then
        MsgBox "The Source File '" & strSource & "' could not be found.  Please validate the" & _
               " location and name of the specifed Source File and try again", vbOKOnly, _
               "File Currently in Use"
    Else
        MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
               Err.Number & vbCrLf & "Error Source: ModExtFiles / CopyFile" & vbCrLf & _
               "Error Description: " & Err.Description, vbCritical, "An Error has Occured!"
    End If
    Exit Function
End Function

All you have to do is copy it into a module and then call it as required. Enjoy!

September 27th, 2010

MS Access – VBA – Rename a File

Ever simply needed to rename a file? Well, once again there are a multitude of ways to accomplish this within MS Access. I have seen numerous postings suggest using a scripting object and then copy the file while renaming the copied version. To me, if all you need is to rename the file, this is a uselessly complicated method. Instead why not simply use the Name function? It can all be accomplished in one clean line of code!!!

Name "C:\OldFileName" AS "C:\NewFileName"

Actually, you can even use the Name command to move and rename a file simultaneously.

Name "C:\OldDir\OldFileName" AS "C:\NewDir\NewFileName"

As you can see this is another versatile command to be aware of.

September 22nd, 2010

VBA – Run/Execute A File

Ever needed to run, execute a file? It could be a *.bat, *.vbs, *.exe, … One common method is to use the shell function. However, we see quite often in the forums and newsgroups regarding issues with it not working and users not getting the synthax right because of spaces in the file paths, etc.

Below is, yet again, a very simple procedure which encapsulates the file to be run/executed with the necessary quotations so that you no longer have any headaches trying to get your Shell function operational. Simply copy the function to a module and call it as indicated below.

'---------------------------------------------------------------------------------------
' Procedure : RunFile
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Run/Execute files from vba (bat, vbs,…)
' 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 - full path including filename and extension
' strWndStyle - style of the window in which the program is to be run
'               value can be vbHide,vbNormalFocus,vbMinimizedFocus
'               vbMaximizedFocus,vbNormalNoFocus or vbMinimizedNoFocus
'
' Usage Example:
' ~~~~~~~~~~~~~~~~
' RunFile("c:\test.bat", vbNormalFocus)
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2010-Feb-05             Initial Release
'---------------------------------------------------------------------------------------
Function RunFile(strFile As String, strWndStyle As String)
On Error GoTo Error_Handler
 
   Shell "cmd /k """ & strFile & """", strWndStyle
 
Error_Handler_Exit:
   On Error Resume Next
   Exit Function
 
Error_Handler:
   MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
   Err.Number & vbCrLf & "Error Source: RunFile" & vbCrLf & "Error Description: " & _
   Err.Description, vbCritical, "An Error has Occured!"
   Resume Error_Handler_Exit
End Function

If however you are interested in opening a file, any type of file, then please refer to my MS Access VBA – Open a File post.

September 21st, 2010

MS Access – VBA – Automatically Adjust User Input to Percentage Values

Have you ever created a control on a form to enter percentage values and had your users complain because they enter whole numbers which get automatically multiplied by 100. So if the user enters 3, it will actually give 300%.

No worries anymore! I created a very simple procedure which will automatically readjust values entered by your users. 3 will automatically be updated to 0.03, which give 3%.

'---------------------------------------------------------------------------------------
' Procedure : ajustPercentage
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Automatically adjust whole number to percentage values
' 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         2010-Sep-21                 Initial Release
'---------------------------------------------------------------------------------------
Function ajustPercentage(sValue As Variant) As Double
On Error GoTo Error_Handler
 
    If IsNumeric(sValue) = True Then            'Only treat numeric values
        If Right(sValue, 1) = "%" Then
            sValue = Left(sValue, Len(sValue) - 1)
            ajustPercentage = CDbl(sValue)
        End If
 
        If sValue > 1 Then
            sValue = sValue / 100
            ajustPercentage = sValue
        Else
            ajustPercentage = sValue
        End If
    Else                                        'Data passed is not of numeric type
        ajustPercentage = 0
    End If
 
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: ajustPercentage" & vbCrLf & _
           "Error Description: " & Err.Description, vbCritical, _
           "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

The one thing to note regarding this procedure is that it is meant for controls/fields that you always expect a percentage value between 0% and 100%. If you expect percentage above 100% this procedure will not help you in that case and you will need to build a custom procedure for that situation.

September 19th, 2010

MS Access – VBA – Import Directory Listing Into A Table

I was asked in a forum how one could automate importing the links (path & Filename) of all the files contained within a specified directory. It is relatively easy to accomplish and the procedure below is one possible method.

The procedure has 2 input variables: strPath which is the full path of the directory whose files you wish to import all the file paths from adn strFilter which is an optional input variable should you wish to refine what type of document is imported (for instance is you only want to import PDFs then you’d enter “pdf”, Word documents “doc”, and so on).

Function ImportDirListing(strPath As String, Optional strFilter As String)
' Author: CARDA Consultants Inc, 2007-01-19
' 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).
'
' strPath = full path include trailing  ie:"c:windows"
' strFilter = extension of files ie:"pdf".  if you want to return
'             a complete listing of all the files enter a value of
'             "*" as the strFilter
On Error GoTo Error_Handler
 
Dim MyFile  As String
Dim db      As Database
Dim sSQL    As String
 
Set db = CurrentDb()
 
'Add the trailing  if it was omitted
If Right(strPath, 1) <> "" Then strPath = strPath & ""
'Modify the strFilter to include all files if omitted in the function
'call
If strFilter = "" Then strFilter = "*"
 
'Loop through all the files in the directory by using Dir$ function
MyFile = Dir$(strPath & "*." & strFilter)
Do While MyFile <> ""
    'Debug.Print MyFile
    sSQL = "INSERT INTO [YourTableName] (YourTableFieldName) VALUES(""" & MyFile & """)"
    db.Execute sSQL, dbFailOnError
    'dbs.RecordsAffected 'could be used to validate that the
                                    'query actually worked
    MyFile = Dir$
Loop
 
Error_Handler_Exit:
    On Error Resume Next
    Set db = Nothing
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: ImportDirListing" & vbCrLf & _
           "Error Description: " & Err.Description, vbCritical, _
           "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

As always, I hope this is useful to someone.

September 17th, 2010

VBA – Word – Update/Fill-in Document Form Fields

Have you ever needed to fill-in or update the form fields of a Word Document from say Access, Excel, … Below is a simple example of how you can do this. In it I demonstrate how to populate a textbox, as well as show you how you can check/uncheck a checkbox.

'---------------------------------------------------------------------------------------
' Procedure : UpdateDoc
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Update/Fill-in a Word document's form fields
' 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         2010-Sep-17                 Initial Release
'---------------------------------------------------------------------------------------
Sub UpdateDoc()
'Requires a reference to the Word object library
Dim oApp        As Word.Application
Dim oDoc        As Word.Document
Dim sDocName    As String
 
On Error Resume Next
    Set oApp = GetObject(, "Word.Application") 'See if word is already running
    If Err.Number <> 0 Then     'Word isn't running so start it
        Set oApp = CreateObject("Word.Application")
    End If
 
On Error GoTo Error_Handler_Exit
    sDocName = "YourWordDocToOpenFullPathAndExtension"
    Set oDoc = oApp.Documents.Open(sDocName)
    oApp.Visible = True
 
    oDoc.FormFields("TextboxName").Result = "NewValue"      'Textbox
    oDoc.FormFields("CheckboxName").CheckBox.Value = True   'Checkbox

Error_Handler_Exit:
    On Error Resume Next
    oDoc.Close True
    oApp.Quit
    Set oDoc = Nothing
    Set oApp = Nothing
    Exit Sub
 
Error_Handler:
    If Err.Number = 5174 Then
        MsgBox "The specified file '" & sDocName & "' could not be found.", _
               vbCritical
    Else
        MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
               "Error Number: " & Err.Number & vbCrLf & _
               "Error Source: UpdateDoc" & vbCrLf & _
               "Error Description: " & Err.Description, _
               vbCritical, "An Error has Occured!"
    End If
    Resume Error_Handler_Exit
End Sub

September 16th, 2010

MS Access – Report – Sequential Numbering of Records

Have you ever needed to add a sequential number to a report’s rows. Well, it is surprising easy to do!

All you need to do is add a textbox into the detail section of your report and set the control’s Control Source property to ‘=1′ and then set the Running Sum property to either ‘Over Group’ or ‘Over All’ depending on what you are trying to acheive. The properties should be as shown below.

 

Textbox properties to setup sequential numbering in an MS Access Report

Textbox properties to setup sequential numbering in an MS Access Report

Close and save your changes and run your report. That’s it! It is that simple.

September 15th, 2010

Launch/Open an MS Access Database Using a VBScript – Part 2

In my previous post launch-open-an-ms-access-database-using-a-vbscript I went over the basic concept of using a VBScript to launch a database.

In this post I would like to demonstrate the true power of VBScript for this type of application.

Say, you are a developer within a structured company network environment and you want to standardize the front-end setup on your users computers without having to sit down at each of their computers, one by one. Well, VBScript to the rescue!

The script below may seem scary, but really isn’t. It start by determining the user’s My Documents location. This is where I have chosen to place the Front-End application of the database. You could always alter this aspect, but it has served me very well in numerous routines. Once it has determine the location it determines the location of the VBScript itself (which will be installed with the Master copy of the Front-end). As such, it copies the Master copy to the user’s My Documents. Then it determines the location of the msaccess.exe required to launch the database and then finally launches it!

Once again, I do hope this helps someone out there as I found it hard to come across this information several years ago when I needed it.

'*******************************************************************************
'Date:		2008-05-27
'Author:	Daniel Pineault / CARDA Consultants Inc.
'Purpose:	This script should be located on a network share in the same
'		directory as the Front-End which it will automatically copy
'		to each user's MyDoc\Subfolder\ and then launch
'		Give your users a link to this script and it will do the rest
'Copyright:	You are free to use the following code as you please so long as
'		this header remains unaltered.
'Revision:	2008-05-27   Initial Release
'*******************************************************************************

	Const MY_DOCUMENTS = &H5&
	Const PROGRAM_FILES = &H26&
 
	Dim objShell
	Dim objFolder
	Dim objFolderItem
	Dim objNetwork
	Dim objFSO
	Dim objShellDb
	Dim DelFoldr
	Dim sMyDocPath
	Dim sProgPath
	Dim sVBSPath
	Dim sAccPath
	Dim sFrontEnd
	Dim sFolder
	Dim sSec
	Dim sUser
	Dim sPath
	Dim sComTxt
 
 
	'Specify the Fullpath and filename of the database to launch
	sFrontEnd = "test.mdb"	'Database name to open
	sFolder = "Databases"		'MyDoc subfolder where the
						'front-end will be copied to
	'If your database is secured by an mdw file specify it below, otherwise
	'leave its value blank
	sSec = "Security.mdw"
 
 
'Determine the location/path of the user's MyDocuments folder
'*******************************************************************************
	Set objShell = CreateObject("Shell.Application")
	Set objFolder = objShell.Namespace(MY_DOCUMENTS)
	Set objFolderItem = objFolder.Self
	sMyDocPath = objFolderItem.Path		'My Documents path
	sPath = sMyDocPath & "\" & sFolder & "\"'Path to front-end
	Set objFolder = objShell.Namespace(PROGRAM_FILES)
	Set objFolderItem = objFolder.Self
	sProgPath = objFolderItem.Path		'Program Files Path

'Determine path of this VBScript
'*******************************************************************************
	sVBSPath = Left(WScript.ScriptFullName,(Len(WScript.ScriptFullName) _
		     - (Len(WScript.ScriptName) + 1)))
 
	'Ensure lastest version of front-end is installed
	Set objNetwork = CreateObject("Wscript.Network")
	sUser = objNetwork.UserName			'User's network username
	Set objFSO = CreateObject("Scripting.FileSystemObject")
 
'Copy a network version of the Front-end to the MyDocs/SubFolder
'*******************************************************************************
	If objFSO.FileExists(sPath & sFrontEnd) Then
 
	Else
  		If objFSO.FolderExists(sPath) then
    			'Delete folder to perform cleanup of old version(s)
    			Set DelFoldr = objFSO.GetFolder(sPath)
    			DelFoldr.Delete
  		End if
  		'Create folder and then copy required file(s)
  		Set objFolderCreate = objFSO.CreateFolder(sPath)
  		objFSO.CopyFile sVBSPath & "\" & sFrontEnd, sPath & _
                  		sFrontEnd, OverWriteExisting
	End if
 
'Determine the location of the MS Access executable
'*******************************************************************************
	Set objShellDb = CreateObject("WScript.Shell")
	'Determine in which folder the Access executable is located
	If objFSO.FileExists(sProgPath &_
                     	     "\Microsoft Office\OFFICE11\msaccess.exe") Then
		sAccPath = sProgPath & "\Microsoft Office\OFFICE11"
	Elseif objFSO.FileExists(sProgPath &_
                                 "\Microsoft Office\OFFICE10\msaccess.exe") Then
  		sAccPath = sProgPath & "\Microsoft Office\OFFICE10"
	Elseif objFSO.FileExists(sProgPath &_
                                 "\Microsoft Office\OFFICE\msaccess.exe") Then
  		sAccPath = sProgPath & "\Microsoft Office\OFFICE"
	End if
 
 
'Launch database
'*******************************************************************************
	'Build the command to launch the database
	sComTxt = chr(34) & sAccPath & "\" & "msaccess.exe" & chr(34) &_
		  " " & chr(34) & sPath & sFrontEnd & chr(34)
	if isNull(sSec)=False AND sSec<>"" Then
		sComTxt = sComTxt & " /wrkgrp " & chr(34) & sVBSPath &_
			  "\" & sSec & chr(34)
		if isNull(sUser)=False AND sUser<>"" Then
			sComTxt = sComTxt & " /user " & sUser
		End if
	End if
 
	objShellDb.Run sComTxt 'Launch the database

Tags:
September 14th, 2010

Launch/Open an MS Access Database Using a VBScript

Have you ever tried to make a shortcut to launch/open an MS Access database and had an error returned because the Target string was too long? Or do you simply need more control/flexibility from your launching routine. In that case, a VBScript is the ideal way to go. Below is the most basic format that the VBScript can take. Simply alter the Script Variables, Save and execute!

I have made the following as flexible as possible so it can open simple database files, as well as security enabled database. It is simply a question of assigning values to the Script Variables or not.

I truly hope this helps you out!

'*******************************************************************************
'Date:		2008-05-27
'Author:	Daniel Pineault / CARDA Consultants Inc.
'		http://www.cardaconsultants.com
'Copyright:	You are free to use the following code as you please so long as
'		this header remains unaltered.
'Purpose:	Launch the specified access database
'Revision:	2008-05-27   Initial Release
'*******************************************************************************

	Dim sAcc
	Dim sFrontEnd
	Dim sSec
	Dim sUser
	Dim objShellDb
	Dim sComTxt
 
'Script Configuration Variable
'*******************************************************************************
	'Specify the Fullpath and filename of the msaccess executable
	sAcc = "C:\Program Files\Microsoft Office\OFFICE11\msaccess.exe"
	'Specify the Fullpath and filename of the database to launch
	sFrontEnd = "D:\Main\My Documents\TestDb.mdb"
	'If your database is secured by an mdw file specify it below, otherwise
	'leave its value blank
	sSec = "C:\Databases\Security.mdw"
	'If your database is secured by an mdw file and you want to specify the
	'username to use specify it below, otherwise leave its value blank
	sUser = ""
 
 
'*******************************************************************************
'*******************************************************************************
'You should not need to edit anything below this point
'*******************************************************************************
'*******************************************************************************

 
'Launch database
'*******************************************************************************
	Set objShellDb = CreateObject("WScript.Shell")
	'Build the command to launch the database
	sComTxt = chr(34) & sAcc & chr(34) &_
		  " " & chr(34) & sFrontEnd & chr(34) 
	if isNull(sSec)=False AND sSec<>"" Then
		sComTxt = sComTxt & " /wrkgrp " & chr(34) & sSec & chr(34)
	End if
	if isNull(sUser)=False AND sUser<>"" Then
		sComTxt = sComTxt & " /user " & sUser
	End if
	objShellDb.Run sComTxt 'Launch the database

Tags:
September 11th, 2010

Web Devlopment Learning Resource – Where to Start

I short while I was asked to sit down with a graphic artist who also was a web developer because they wanted me to teach them what I knew because I had commented on their work to their client (who happened to also be one of my database clients).

I was more than happy to oblige, as I have no problem trying to help someone else out when I can.

They basically knew how-to use Dreamweaver, but that was about it. So I went over a number of things that I have learnt in the past few years and thought I should post them here should they be useful to someone else. So here goes…

The first aspect I wanted to emphasize was the importance of clean code! What does this entail, a couple of simple things really:

  • CSS driven design
  • Separate files for CSS, JS
  • Clean directory structure. Don’t dump everything into the root folder, but rather make a simple directory structure (images, js, css, …)
  • When appropriate add comments within your code so you can find yourself at a later date.
  • Ensure that your design is cross-browser compliant. Long gone are the days that Internet Explorer is the only web browser, so make sure your website works in the other browsers (Firefox, Opera, Safari, and many more…)
  • Ensure your code is W3C compliant by simply testing each of your pages with their Free Validation tools (links provided below). Take some time to get to know the standards and utilize all the free information this organisation provides.

 

W3C Links

 

Other Useful Links

 

Javascript and JQuery

At some point or another you will be faced with the need to add some form of automation to your webpage. At that point you will need to look into javascripting,… I would urge you to simply go straight to learning JQuery instead. It actually use javascript, but is simpler and comes with many already existing functions and samples. Believe me, this will save you time and frustrations in the long run and will give you tremendous capabilities right from the start. Another beauty is that unlike custom javascript functions, jQuery is crossbrowser compatible! This will save you countless hours of testing, troubleshooting and finding browser hacks!!! Check it out for yourself at: http://jquery.com/

I truly hope this brief article gives you a jump start into web development and various online resources at your disposal. Have fun!

September 10th, 2010

VBA – Word – Enumerate/List All the Document Bookmarks

Similarily to my previous post entitled VBA – Word – Enumerate/List All Form Fields you can just as easily produce a listing of all the Bookmarks of a Word document. The following procedure does exactly that.

'---------------------------------------------------------------------------------------
' Procedure : EnumerateDocBkMrks
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Generate a listing of all the Bookmarks containing within the
'             specified word document and print them to the immediate window.
' 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         2010-Sep-10                 Initial Release
'---------------------------------------------------------------------------------------
Function EnumerateDocBkMrks(sFileName As String)
On Error GoTo Error_Handler
'Requires a reference to the Word object library
Dim oApp                As Word.application
Dim oDoc                As Word.Document
Dim dBkMrk              As Bookmark
 
On Error Resume Next
    Set oApp = GetObject(, "Word.Application")
    If Err.Number <> 0 Then 'Word isn't running so start it
        Set oApp = CreateObject("Word.Application")
    End If
On Error GoTo 0
 
    Set oDoc = oApp.Documents.Open(sFileName)
    oApp.Visible = False 'Control whether or not Word becomes
                         'visible to the user
    
    'Loop through each form field
    For Each dBkMrk In oDoc.Range.Bookmarks
        Debug.Print dBkMrk.Name
    Next
 
Error_Handler_Exit:
    On Error Resume Next
    oDoc.Close False
    oApp.Quit
    Set oDoc = Nothing
    Set oApp = Nothing
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
            "     Error Number: " & Err.Number & vbCrLf & _
            "     Error Source: EnumerateDocBkMrks" & vbCrLf & _
            "     Error Description: " & Err.Description, _
            vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

September 10th, 2010

VBA – Word – Enumerate/List All the Document Form Fields

Have you ever started coding some vba to manipulate a Word document’s form fields and started going back and forth between the word document and the VBE. This can work if you have a few form fields, but becomes very tiresome when dealing with large form. As such, I created a very simple procedure to extract a list of the form fields in one shot and then I could continue my work in peace. I hope the following saves you some time and frustrations too.

'---------------------------------------------------------------------------------------
' Procedure : EnumerateDocFrmFlds
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Generate a listing of all of the form fields containing within the
'             specified word document and print them to the immediate window.
' 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         2010-Sep-10                 Initial Release
'---------------------------------------------------------------------------------------
Function EnumerateDocFrmFlds(sFileName As String)
On Error GoTo Error_Handler
'Requires a reference to the Word object library
Dim oApp                As Word.application
Dim oDoc                As Word.Document
Dim dFormField          As FormField
 
On Error Resume Next
    Set oApp = GetObject(, "Word.Application")
    If Err.Number <> 0 Then 'Word isn't running so start it
        Set oApp = CreateObject("Word.Application")
    End If
On Error GoTo 0
 
    Set oDoc = oApp.Documents.Open(sFileName)
    oApp.Visible = False 'Control whether or not Word becomes
                         'visible to the user
    
    'Loop through each form field
    For Each dFormField In oDoc.FormFields()
        Debug.Print dFormField.Name
    Next
 
Error_Handler_Exit:
    On Error Resume Next
    oDoc.Close False
    oApp.Quit
    Set oDoc = Nothing
    Set oApp = Nothing
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
            "     Error Number: " & Err.Number & vbCrLf & _
            "     Error Source: EnumerateDocFrmFlds" & vbCrLf & _
            "     Error Description: " & Err.Description, _
            vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

September 9th, 2010

VBA – Word – Open a Word Document

If you have ever needed to open a Word document and are looking for an alternative method to the Application.FollowHyperlink method, then the following procedure using Word automation should do the trick.

'---------------------------------------------------------------------------------------
' Procedure : OpenWordDoc
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Open the specified Word document
' 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         2010-Sep-09                 Initial Release
'---------------------------------------------------------------------------------------
Function OpenWordDoc(sFileName As String)
On Error GoTo Error_Handler
'Requires a reference to the Word object library
Dim oApp As Word.Application
Dim oDoc As Word.Document
 
On Error Resume Next
    Set oApp = GetObject(, "Word.Application")
    If Err.Number <> 0 Then 'Word isn't running so start it
        Set oApp = CreateObject("Word.Application")
    End If
On Error GoTo 0
 
    Set oDoc = oApp.Documents.Open(sFileName)
    oApp.Visible = True
 
Error_Handler_Exit:
    On Error Resume Next
    Set oDoc = Nothing
    Set oApp = Nothing
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
            "Error Number: " & Err.Number & vbCrLf & _
            "Error Source: OpenWordDoc" & vbCrLf & _
            "Error Description: " & Err.Description, _
            vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

September 9th, 2010

VBA – Excel – Run an Excel Macro

Have you ever had the need to run an Excel workbook macro from another application, whether it be Word, Access,… I did, so I develop the following simple little procedure to do exactly that.

'---------------------------------------------------------------------------------------
' Procedure : RunXLSMacro
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Open the specifed Excel workbook and run the specified macro and then
'             close the 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         2010-Sep-09                 Initial Release
'---------------------------------------------------------------------------------------
Function RunXLSMacro(sFile As String, sMacroName As String) As String
'Requires a reference to the Microsoft Excel xx.0 Object Library
On Error GoTo Error_Handler
    Dim xlApp       As Object
    Dim xlWb        As Object
    Dim sFileName   As String
 
    Set xlApp = CreateObject("Excel.Application") 'Create an Excel instance
    Set xlWb = xlApp.Workbooks.Open(sFile, True)  'Open the specified workbook
    xlApp.Visible = True                          'Control whether or not to show Excel
                                                    'to your user
    
    sFileName = Right(sFile, Len(sFile) - InStrRev(sFile, "\"))
 
    xlApp.Run sFileName & "!" & sMacroName         'Execute the specified macro

Error_Handler_Exit:
    On Error Resume Next
    xlWb.Close (True)                             'Save the excel workbook
    xlApp.Quit                                    'Close/Quit Excel
    Set xlWb = Nothing
    Set xlApp = Nothing
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
            "Error Number: " & Err.Number & vbCrLf & _
            "Error Source: RunXLSMacro" & vbCrLf & _
            "Error Description: " & Err.Description, _
            vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

September 9th, 2010

MS Access – VBA – Calculate the Number of Years

The following function accepts two dates as input variables and will return the number of years between those two dates. If you are looking to get a greater level of precision (months, days) then take a look at my post entitled MS Access – Calculate the Age

'---------------------------------------------------------------------------------------
' Procedure : NoYrs
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Calculate the number of Years between two dates
' 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         2010-Sep-09                 Initial Release
'---------------------------------------------------------------------------------------
Function NoYrs(Date1 As Date, Date2 As Date) As Integer
On Error GoTo Error_Handler
    Dim Y       As Integer
    Dim Temp1   As Date
 
    Temp1 = DateSerial(Year(Date2), Month(Date1), Day(Date1))
    Y = Year(Date2) - Year(Date1) + (Temp1 > Date2)
    NoYrs = Y
 
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: NoYrs" & vbCrLf & _
            "Error Description: " & Err.Description, _
            vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

September 9th, 2010

MS Access – VBA – ADO vs. DAO

A common question asked in numerous forums and discussion groups is:

  • Which is better: ADO or DAO?
  • Should I be using ADO or DAO in my code?

Thruthfully, there is no answer that applies for everyone. It all depends on what you are doing!

Some people argue back and forth that ADO or DAO is easier to code, or more powerful…  I’m not even going to tackle this subject as a lot of it is subjective and dependent on what you are doing.   They each offer pros and cons to the developper. That said;

If you are developing an MS Access database (back-end) then DAO is probably your best bet as it is optimized for Jet/ACE.  It should also be noted, from what I have read, that Microsoft recommends DAO for Jet data and as such is typically faster than ADO in this scenario.

On the other hand, if you are developing an Access Data Project (.adp) in conjunction with an SQL Server database (back-end), it is normally recommended that you use ADO. 

So based on this it become apparent that, it’s not a matter of whether it’s an ADP or an MDB/ACCDB, but rather where your data is stored and whether or not you will be using the Jet/ACE database engine or not.  If you are utilizing the default Jet/ACE database engine then DAO is typically the best route to go.  If not, then ADO is best.

September 3rd, 2010

VBA – Sending Faxes VBA

Sending Faxes of a Document using VBA (Microsoft Shared Fax Driver)

 

I had a requirement for a database to be able to send faxes directly from within the database. At the time, I looked high and low and couldn’t find anything on the subject using the Microsoft Shared Fax Driver (Fax printer). It is only recently that I came across a website that covered the subject very well (Murphy’s Law!).

MSDN Article

The following is a slightly modified version of the code found in the MSDN Article. I use a temporary table to populate the recipient of my broadcast (multiple recipient fax).

'---------------------------------------------------------------------------------------
' Procedure  : SendBroadCast
' Author     : CARDA Consultants Inc.
' Website    : http://www.cardaconsultants.com
' Code Source: http://msdn2.microsoft.com/en-us/library/ms693479.aspx
' Purpose    : Send Broadcast fax (send fax to multiple recipients)
' References : requires 'Microsoft Fax Service Extended COM Type Library'
' 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:
' ~~~~~~~~~~~~~~~~
' strDoc - path and filname of the document to be faxed
'---------------------------------------------------------------------------------------
'
Function SendBroadCast(strDoc As String)
 
Dim objFaxDocument As New FAXCOMEXLib.FaxDocument
Dim collFaxRecipients As FaxRecipients
Dim JobId As Variant
Dim strMsg As String
 
'Error handling
On Error GoTo Error_Handler
 
'Set the fax body
objFaxDocument.Body = strDoc
 
'Name the document
objFaxDocument.DocumentName = "Database Fax"
 
'Get the recipients collection
Set collFaxRecipients = objFaxDocument.Recipients
 
'Update the table from which the info is pull to generate the fax recipient list
DoCmd.SetWarnings False 'Turn off warning messages so it is transparent to the user
DoCmd.OpenQuery "Qry_Need To Be Faxed", acViewNormal
DoCmd.SetWarnings True 'Turn back on warning messages

'Add the recipients
With collFaxRecipients
    'Using the table created by the above run query loop through the record
    'To populate the fax recipient list
    Dim rst As DAO.Recordset
    Set rst = CurrentDb.OpenRecordset("Temp01")
    If rst.RecordCount > 0 Then 'ensure there is data
        rst.MoveLast  'goto the last recordset
        Do Until rst.BOF  'beginning of file
           'perform a desired action
           .Add rst![Fax], rst![Company]
           rst.MovePrevious
        Loop
    Else
        MsgBox "There are no faxes to be sent at this time!", vbInformation
    End If
 
End With
 
'Display number of recipients
strMsg = "Total Number of Recipients: " & collFaxRecipients.Count & vbCrLf
 
'Display recipient information
Dim i As Long
For i = 1 To collFaxRecipients.Count
    strMsg = strMsg & "Recipient number " & i & ": " & collFaxRecipients.Item(i).Name & _
             ", " & collFaxRecipients.Item(i).FaxNumber & vbCrLf
Next
MsgBox strMsg, vbInformation, "The following faxes are being processed."
 
'Load the default sender
objFaxDocument.Sender.LoadDefaultSender
 
'Group the broadcast receipts
objFaxDocument.GroupBroadcastReceipts = True
 
'Connect to the fax server, submit the document, and get back the
'job ID array. "" indicates the local server.
JobId = objFaxDocument.Submit("")
 
'UBound finds the size of the array
'Display jobIDs for each of the fax jobs
'For n = 0 To UBound(JobId)
'    MsgBox "The Job ID is " & JobId(n)
'Next

'Remove the recipients from the collection. If you don't take this step,
'and run this code again without closing the program, the recipients
'collection will retain the recipients and keep adding more recipients.
'The count and item numbering will change as you remove the items, so
'just remove item (1) Count times
Dim lCount As Long
lCount = collFaxRecipients.Count
For i = 1 To lCount
    collFaxRecipients.Remove (1)
Next
Exit Function
 
Error_Handler:
    'Implement error handling at the end of your subroutine. This
    'implementation is for demonstration purposes
    If Err.Number = -2147024864 Then
        MsgBox "You currently have the document to be faxed open and are therefore" & _
               " stopping the fax from being sent.  Please close the document in " & _
               "question and then try again.", vbInformation, "Your Fax cannot be " & _
               "sent at this time"
    Else
        MsgBox "Error number: " & Err.Number & ", " & Err.Description
    End If
End Function

September 3rd, 2010

Word – VBA – Print a Word Document

The following code will print out a word document.

'---------------------------------------------------------------------------------------
' Procedure : PrintDoc
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Print a Word Document
' 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:
' ~~~~~~~~~~~~~~~~
' strDoc - The path and filename of the document to be printes
' intCopies - The number of copies to be printed
'
' Usage:
' ~~~~~~~~~~~~~~~~
' PrintDoc("c:\management\evaluation.doc",1)
'---------------------------------------------------------------------------------------
Function PrintDoc(strDoc As String, intCopies As Integer)
 
   Dim WordObj As Object
 
   Set WordObj = CreateObject("Word.Application")
 
   WordObj.Documents.Open strDoc
   WordObj.PrintOut Background:=False, Copies:=intCopies
   WordObj.Documents.Close SaveChanges:=wdDoNotSaveChanges
   WordObj.Quit
 
   Set WordObj = Nothing
 
 End Function

September 3rd, 2010

VBA – Word – Open Word using Late Binding

The following procedure will launch MS Word. The beauty is it uses late binding so you do not need to use reference libraries and as such avoid/minimize versioning issues. This same procedure can easily be modified to launch just about any MS Office application by simply changing the “Word.Application” portions of the code to correspond with the application you are trying to automate.

A few other strings used for common MS Office application are:

  • Excel – “Excel.Application”
  • Access – “Access.Application”
  • Publisher – “Publisher.Application”
  • PowerPoint – “Powerpoint.Application”

Sub LaunchWord()
Dim objApp As Object
 
    'See if Word is already running
    On Error Resume Next
    Set objApp = GetObject(, "Word.Application")
 
    If Err.Number <> 0 Then
        'Launch a new instance of Word
        Err.Clear
        On Error GoTo Error_Handler
        Set objApp = CreateObject("Word.Application")
        objApp.Visible = True 'Make the application visible to the user (if wanted)
    End If
 
Exit Sub
 
Error_Handler:
    MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
    Err.Number & vbCrLf & "Error Source: LaunchWord" & vbCrLf & "Error Description: " & _
    Err.Description, vbCritical, "An Error has Occured!"
    Exit Sub
End Sub

September 3rd, 2010

VBA – Excel – Execute/Run an Excel Worksheet Function

Have you ever needed to use an Excel function within one of your databases, or other application. Below is a generic example of how you can call just about any Excel function using VBA to extend your database’s functionalities even further.

'---------------------------------------------------------------------------------------
' Procedure : GetXLWkSHtFuncVal
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Execute an Excel Worksheet Function from MS Access
' 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         2010-Jan-31             Initial Release
'---------------------------------------------------------------------------------------
Function GetXLWkSHtFuncVal()
   Dim xlApp      As Object
On Error GoTo Error_Handler
 
   Set xlApp = CreateObject("Excel.Application")
   xlApp.Visible = False   'Control whether or not Excel should be visible to
                           'the user or not.
   
   'This is a generic example using the NormInv(), but you can do the same with just
   'about any other Excel Worksheet function.
   GetXLWkSHtFuncVal = xlApp.WorksheetFunction.NormInv(0.25, 4, 1)
 
   xlApp.Quit           'Close the instance of Excel we create

Error_Handler_Exit:
   On Error Resume Next
   Set xlApp = Nothing
   Exit Function
 
Error_Handler:
   MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
   Err.Number & vbCrLf & "Error Source: GetXLWkSHtFuncVal" & vbCrLf & "Error Description: " & _
   Err.Description, vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

September 3rd, 2010

VBA – Excel – Clear/Delete an Excel Worksheet

Have you ever needed to blank an Excel worksheet from an Access (or other programs as well – Word, PowerPoint, …) database? The following procedure does exactly that!

'---------------------------------------------------------------------------------------
' Procedure : ClearXLSWrkSht
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Clear the specified worksheet in a given excel workbook from MS Access
' 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     Excel workbook filename with full path (ie: "C:\test.xls")
' sXLSWrkSht   Excel worksheet to be cleared (ie: "Sheet1")
'
' Usage Example:
' ~~~~~~~~~~~~~~~~
' ClearXLSWrkSht("C:\test.xls", "Sheet1")
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2010-Jan-28             Initial Release
'---------------------------------------------------------------------------------------
Sub ClearXLSWrkSht(sXLSFile As String, sXLSWrkSht As String)
   Dim xlApp      As Object
   Dim xlBook     As Object
   Dim xlSheet    As Object
On Error GoTo Error_Handler
 
   Set xlApp = CreateObject("Excel.Application")
   xlApp.Visible = True 'Control whether or not Excel should be visible to
                        'the user or not.
   Set xlBook = xlApp.Workbooks.Open(sXLSFile)  'Open the workbook
   Set xlSheet = xlBook.Worksheets(sXLSWrkSht)  'Worksheet we are working with
   
   xlSheet.Cells.Select
   xlSheet.Cells.ClearContents   'Clear the contents
   
   xlBook.Close True 'Close and save the workbook
   xlApp.Quit        'Close the instance of Excel we create

Error_Handler_Exit:
   On Error Resume Next
   Set xlSheet = Nothing
   Set xlBook = Nothing
   Set xlApp = Nothing
   Exit Sub
 
Error_Handler:
   MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
   Err.Number & vbCrLf & "Error Source: ClearXLSWrkSht" & vbCrLf & "Error Description: " & _
   Err.Description, vbCritical, "An Error has Occured!"
   Resume Error_Handler_Exit
End Sub

September 3rd, 2010

VBA – Excel – List the Sheet Names of an Excel Workbook

'---------------------------------------------------------------------------------------
' Procedure : ListXlsSheets
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : List the sheet name of an Excel 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:
' ~~~~~~~~~~~~~~~~
' sFile - The Excel file to list the sheets
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2008-Jul-15                 Initial Release
'---------------------------------------------------------------------------------------
Function ListXlsSheets(sFile As String)
On Error GoTo Error_Handler
    Dim NumSheets   As Integer
    Dim i           As Integer
    Dim xlApp       As Object
    Dim xlWrkBk     As Object
    Dim xlWrkSht    As Object
 
    On Error Resume Next
    Set xlApp = 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 xlApp = CreateObject("excel.application")
    Else
        On Error GoTo Error_Handler
    End If
 
    xlApp.Visible = False 'make excel visible or not to the user
    Set xlWrkBk = xlApp.Workbooks.Open(sFile)
 
    NumSheets = xlWrkBk.Sheets.Count
    For i = 1 To NumSheets
        Debug.Print i & " - " & xlWrkBk.Sheets(i).Name
    Next i
 
    xlWrkBk.Close False
    xlApp.Close
 
    Set xlWrkSht = Nothing
    Set xlWrkBk = Nothing
    Set xlApp = Nothing
 
Exit Function
 
Error_Handler:
    If Err.Number <> 438 Then
        MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
        Err.Number & vbCrLf & "Error Source: ListXlsSheets" & vbCrLf & "Error Description: " & _
        Err.Description, vbCritical, "An Error has Occured!"
        Exit Function
    Else
        Resume Next
    End If
 
End Function

September 3rd, 2010

VBA – Excel – Print an Excel WorkSheet Range

'---------------------------------------------------------------------------------------
' Procedure : PrinWrkShtRng
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Print a specified worksheet range
' Copyright : It is not to be altered or distributed,
'             except as part of an application.
'             You are free to use it in any application,
'             provided the copyright notice is left unchanged.
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' strWrkBk      Workbook file name(full path and filename)
' strWrkSht     Worksheet name which whose range are to be printed
' strRng        Worksheet Range to be printed
'
'
' Revision History:
' Rev       Date(yyyy/mm)           Description
' **************************************************************************************
' 1         2008-Feb                Initial Release
'---------------------------------------------------------------------------------------
Function PrinWrkShtRng(strWrkBk As String, strWrkSht As String, strRng As String)
On Error GoTo PrinWrkShtRng_Error
    Dim xlApp       As Object
    Dim xlWrkBk     As Object
    Dim xlWrkSht    As Object
 
    On Error Resume Next
    Set xlApp = 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 PrinWrkShtRng_Error
        Set xlApp = CreateObject("excel.application")
    Else
        On Error GoTo PrinWrkShtRng_Error
    End If
 
    xlApp.Visible = True 'make excel visible to the user
    Set xlWrkBk = xlApp.Workbooks.Open(strWrkBk)
 
    Set xlWrkSht = xlApp.Worksheets(strWrkSht)
 
    With xlWrkSht.PageSetup
        .PrintArea = strRng
        .Zoom = False
        .FitToPagesTall = 1
        .FitToPagesWide = 1
        .Orientation = xlLandscape
    End With
 
    xlWrkSht.PrintOut Copies:=1
 
    xlWrkBk.Close False
    xlApp.Close
 
    Set xlWrkSht = Nothing
    Set xlWrkBk = Nothing
    Set xlApp = Nothing
 
Exit Function
 
PrinWrkShtRng_Error:
    MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
    Err.Number & vbCrLf & "Error Source: PrinWrkShtRng" & vbCrLf & _
    "Error Description: " & Err.Description, vbCritical, "An Error has Occured!"
    Exit Function
 
End Function

September 3rd, 2010

VBA – Excel – Delete a Worksheet from a Workbook

'---------------------------------------------------------------------------------------
' Procedure : DelWrkSht
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Delete a worksheet from an Excel workbook
' Copyright : It is not to be altered or distributed,
'             except as part of an application.
'             You are free to use it in any application,
'             provided the copyright notice is left unchanged.
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' strWrkBk      Workbook to delete the worksheet in/from (full path and filename)
' strWrkSht     Worksheet to be deleted
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2008-Feb                 Initial Release
'---------------------------------------------------------------------------------------
Function DelWrkSht(strWrkBk As String, strWrkSht As String) As Boolean
    Dim xlApp       As Object
    Dim xlWrkBk     As Object
 
    On Error Resume Next
    Set xlApp = 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 DelWrkSht_Error
        Set xlApp = CreateObject("excel.application")
    Else
        On Error GoTo DelWrkSht_Error
    End If
 
    Set xlWrkBk = xlApp.Workbooks.Open(strWrkBk)
 
        xlApp.DisplayAlerts = False 'surpress user confirmation prompt
        xlApp.Worksheets(strWrkSht).Delete
        xlApp.DisplayAlerts = True  'reengage user confirmation prompt
        xlApp.Visible = True
 
    Set xlApp = Nothing
    Set xlWrkBk = Nothing
 
    DelWrkSht = True
 
Exit Function
 
DelWrkSht_Error:
    DelWrkSht = False
    If Err.Number = 9 Then
        'Worksheet not found
        MsgBox "Worksheet '" & strWrkSht & "' not found in Workbook '" & strWrkBk & "'", vbCritical
        Exit Function
    ElseIf Err.Number = 1004 Then
        'Workbook not found
        MsgBox "Unable to locate Workbook '" & strWrkBk & "'", vbCritical
        Exit Function
    Else
        'Othere Errors
        MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
        Err.Number & vbCrLf & "Error Source: basExcel / DelWrkSht" & vbCrLf & _
        "Error Description: " & Err.Description, vbCritical, "An Error has Occured!"
        Exit Function
    End If
End Function

September 3rd, 2010

VBA – Create an Outlook Contact

The following procedure illustrates how easily one can use VBA to create an Outlook Contact using Late binding so no references are required. Also note, there are many more contact properties available to the VBA programmer, for a full list consult the Outlook Help file.

Function AddOlContact()
On Error GoTo Error_Handler
    Const olContactItem = 2
    Dim olApp As Object
    Dim Ctct As Object
 
    Set olApp = CreateObject("Outlook.Application")
    Set olContact = olApp.CreateItem(olContactItem)
 
    With olContact
        .FirstName = "Daniel"
        .LastName = "Alba"
        .JobTitle = ""
        .CompanyName = "MINI CARDA"
        .BusinessAddressStreet = "22 ClearPoint"
        .BusinessAddressCity = "Pointe-Claire"
        .BusinessAddressState = "Quebec"
        .BusinessAddressCountry = "Canada"
        .BusinessAddressPostalCode = "H9X 3A6"
        .BusinessTelephoneNumber = "(514) 488-0956"
        .BusinessFaxNumber = ""
        .Email1Address = "mini@mini.com"
        .MobileTelephoneNumber = ""
        .Save 'use .Display if you wish the user to see the contact pop-up
    End With
 
Error_Handler_Exit:
    On Error Resume Next
    Set olContact = Nothing
    Set olApp = Nothing
    Exit Function
 
Error_Handler:
    MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
    Err.Number & vbCrLf & "Error Source: AddOlContact" & vbCrLf & "Error Description: " & _
    Err.Description, vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function