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

Leave a Reply









Spam protection by WP Captcha-Free