473,399 Members | 2,858 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

VBA Solution for Simulating Excel VLookup in Access

Looking up values from an Access table is simple. Simulating the 'Range Lookup' functionality from Excel's VLookup formula is a bit trickier.

For those that aren't familiar with this, it allows you to look up the next smallest value to what you provided, and return any corresponding field from the table. Very useful for looking up things like currency exchange rates, tax rates, etc., where there might not be an entry for every day/income level/etc.

This code is based on a hard-coded solution I found at:

http://www.access-programmers.co.uk/forums/showthread.php?t=69080

Thanks to ByteMyzer for providing the concept, I've just made it into a flexible VBA function.

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. Public Function AccessVLookup(strTable As String, strLookupField As String, _
  4.     varLookupValue As Variant, strReturnField As String, _
  5.     Optional strCriteriaField As String, Optional varCriteriaValue As Variant) As Variant
  6.  
  7. 'Aaron Ringer 26 Feb 08
  8.  
  9. 'Simulates the Excel VLookup function in Access, complete with Range Lookup argument.
  10. 'I've used it to look up currency exchange rates, to get the XRate active at the given date.
  11. 'It means that there doesn't have to be an entry on the given date, it'll find the next lowest value.
  12. 'Can be used to look up anything, as long as the lookup field contains numeric data.
  13. 'Returns zero if nothing found.
  14.  
  15. 'strTable = Name of lookup table.
  16. 'strLookupField = Name of field to search.
  17. 'varLookupValue = Value to look for in lookup field.
  18. 'strReturnField = Field to return value from.
  19.  
  20. 'Example:
  21. 'Gets the exchange rate for the given currency active as of today.
  22. 'dblExchangeRate = AccessVLookup("tblCurrencyExchangeRate", "EffectiveDate", Date, "ExchangeRate", "CurrencyID", lngCurrencyID)
  23.  
  24.   Dim strSQL As String
  25.   Dim qdf As DAO.QueryDef
  26.   Dim rst As DAO.Recordset
  27.  
  28.   strSQL = "SELECT "
  29.   strSQL = strSQL & "T1." & strReturnField
  30.   strSQL = strSQL & " FROM " & strTable & " AS T1 "
  31.   strSQL = strSQL & "WHERE T1." & strLookupField & "="
  32.   strSQL = strSQL & "(SELECT Max(T2." & strLookupField & ") "
  33.   strSQL = strSQL & "FROM " & strTable & " AS T2 "
  34.   strSQL = strSQL & "WHERE T2." & strLookupField & " <= "
  35.   strSQL = strSQL & "[LookupValue]"
  36.  
  37.   If Len(strCriteriaField) > 0 Then
  38.     strSQL = strSQL & " AND [" & strCriteriaField & "]"
  39.     strSQL = strSQL & " = " & varCriteriaValue
  40.   End If
  41.  
  42.   strSQL = strSQL & ")"
  43.  
  44.   Set qdf = CurrentDb.CreateQueryDef("", strSQL)
  45.  
  46.   qdf.Parameters("LookupValue") = varLookupValue
  47.   Set rst = qdf.OpenRecordset
  48.   If rst.RecordCount > 0 Then AccessVLookup = rst.Fields(strReturnField)
  49.  
  50.   rst.Close
  51.   qdf.Close
  52.   Set rst = Nothing
  53.   Set qdf = Nothing
  54.  
  55. End Function
  56.  
I've spent a bit of time on it, but haven't thoroughly optimised it - if anyone can suggest any improvements, please let us all know.

Enjoy!
Mar 18 '08 #1
1 6765
I've found a flaw in the function which meant that, if there are several records with the same LookupValue, it might not return the right one.

Fixed function:

Expand|Select|Wrap|Line Numbers
  1. Public Function AccessVLookup(strTable As String, strLookupField As String, _
  2.     varLookupValue As Variant, strReturnField As String, _
  3.     Optional strCriteriaField As String, Optional varCriteriaValue As Variant) As Variant
  4.  
  5. 'Aaron Ringer 28 Jan 09
  6.  
  7. 'Simulates the Excel VLookup function in Access, complete with Range Lookup argument.
  8. 'I've used it to look up currency exchange rates, to get the XRate active at the given date.
  9. 'It means that there doesn't have to be an entry on the given date, it'll find the next lowest value.
  10. 'Can be used to look up anything, as long as the lookup field contains numeric data.
  11. 'Returns zero if nothing found.
  12.  
  13. 'strTable = Name of lookup table.
  14. 'strLookupField = Name of field to search.
  15. 'varLookupValue = Value to look for in lookup field.
  16. 'strReturnField = Field to return value from.
  17.  
  18. 'Example:
  19. 'Gets the exchange rate for the given currency active as of today.
  20. 'dblExchangeRate = AccessVLookup("tblCurrencyExchangeRate", "EffectiveDate", Date, "ExchangeRate", "CurrencyID", lngCurrencyID)
  21.  
  22.   Dim strSQL As String
  23.   Dim qdf As DAO.QueryDef
  24.   Dim rst As DAO.Recordset
  25.  
  26.   strSQL = "SELECT "
  27.   strSQL = strSQL & "T1." & strReturnField
  28.   strSQL = strSQL & " FROM " & strTable & " AS T1 "
  29.   strSQL = strSQL & "WHERE T1." & strLookupField & "="
  30.   strSQL = strSQL & "(SELECT Max(T2." & strLookupField & ") "
  31.   strSQL = strSQL & "FROM " & strTable & " AS T2 "
  32.   strSQL = strSQL & "WHERE T2." & strLookupField & " <= "
  33.   strSQL = strSQL & "[LookupValue]"
  34.  
  35.   If Len(strCriteriaField) > 0 Then
  36.     strSQL = strSQL & " AND [" & strCriteriaField & "]"
  37.     strSQL = strSQL & " = " & varCriteriaValue
  38.   End If
  39.  
  40. 'Need this extra criteria, or may return value from other record with same value in strLookupField.
  41.   strSQL = strSQL & " AND T1." & strCriteriaField
  42.   strSQL = strSQL & " = " & varCriteriaValue
  43.  
  44.   strSQL = strSQL & ")"
  45.  
  46.   Set qdf = CurrentDb.CreateQueryDef("", strSQL)
  47.  
  48.   qdf.Parameters("LookupValue") = varLookupValue
  49.   Set rst = qdf.OpenRecordset
  50.   If rst.RecordCount > 0 Then AccessVLookup = rst.Fields(strReturnField)
  51.  
  52.   rst.Close
  53.   qdf.Close
  54.   Set rst = Nothing
  55.   Set qdf = Nothing
  56.  
  57. End Function
  58.  
Jan 27 '09 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

0
NeoPa
by: NeoPa | last post by:
VlookUp or Vertical LookUp is a function that enables Excel to ‘Find’ related items from within a range stored elsewhere. Elsewhere can mean another excel workbook on another PC, but can also mean a...
5
by: catlover30 | last post by:
HI, I need help with excel VLOOKUP! I am at a new job and really trying to solve this without asking anyone at work, since they seem th expect me to know this. What I am trying to acheive is the...
3
by: Widge | last post by:
I have made a spreadsheet that will calculate the distance from a set of addresses to a specified postcode in Excel. I'm looking to move this to Access so I can start thinking about hooking it up to...
3
by: D.Stone | last post by:
I'm trying to import an Excel spreadsheet into an existing Access table using Office 2003. Ultimately, the plan is to do it programmatically using TransferSpreadsheet, but to check that the file...
0
by: acarrazco | last post by:
Hello, I am totaly new to VBA and I'm trying to modify a macro that was given to me but it doesn't seem to be working. I'm trying to extract data from three excel spreadsheets, put it into a combined...
3
by: sejal17 | last post by:
hello Can any one tell me how to read multiple worksheets from a single excel file.I have stored that excel in xml file.so i want to read that xml that has multiple worksheet.And i want to store...
3
by: sejal17 | last post by:
hello Can any one tell me how to read multiple worksheets from a single excel file.I have stored that excel in xml file.so i want to read that xml that has multiple worksheet.And i want to store...
4
by: John Brock | last post by:
I have a .NET application that, among other things, creates Excel workbooks, and I have run into a very strange problem involving formulas on one worksheet that reference values on another...
1
by: Monusonu | last post by:
Hi Expert, I am trying to get the value from excel formula cell using POI. My code works fine for less complex formula cells, but fails or returns error code for complex formula cells. Following...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.