473,795 Members | 2,914 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

VBA Solution for Simulating Excel VLookup in Access

13 New Member
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 6793
scubasteve
13 New Member
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
4014
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 range in the current worksheet. In any Range reference in Excel, a ’$’ preceeding an element of the address, simply tells Excel not to be clever when copying or dragging the formula to other cells. Notice the formulas displayed in column B below:...
5
17641
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 same thing as a FULL OUTER JOIN if you are familiar with sql. I tried to do this is in access, but access does not support full joins. Anyhow: I have two email lists, one woth 2500 entries, one with 2600. They are located in same worksheet, one in...
3
1803
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 a webpage. The main problem is the fact that I don't have a CLUE how to perform the lookup in Access. Basically we have 3 sheets. 1) where you enter your postcode and radius to search by, 2) a list of suppliers, their addresses and postcodes ... with...
3
5327
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 has no problems, I've done it manually with the Import Spreadsheet wizard. The worksheet has 43 rows, and I import a named range defined as "=Sheet1!$C:$E". The import works, but I get a table with 64K rows, all but 43 being blank!
0
3479
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 one which creates a pivot table and sorts it into different fromats. Here is the code, can any body help? Sub Update_Land_Actuals() On Error Resume Next If InputBox("Enter password to continue", "Centex Homes") <> "***" Then Exit Sub...
3
6252
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 that multiple worksheet data in different table.How can i do it.Below is my xml file. <?xml version="1.0"?> <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" ...
3
5403
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 that multiple worksheet data in different table.How can i do it.Below is my xml file. <?xml version="1.0"?> <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office"...
4
1786
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 worksheet. The text I write into, let's say, cell A25 on Sheet1 (using .NET) looks something like this: =VLOOKUP(RC,'Sheet2'!A:X,6,FALSE) On the completed workbook this turns into:
1
11061
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 is the code I am using to get values:- public class POIMain{ public POIMain() { } public static void main(String args) { try{
0
9673
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9522
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10448
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10167
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10003
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9046
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5566
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4114
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3730
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.