Searching for Data With a User Form in Excel Populated user form - KING OF EXCEL

KING OF EXCEL

KINGEXCEL.INFO ( KING OF EXCEL ) Welcome KINGEXCEL.INFO - Nothing Is Unable ... About Excel Tricks, Learning VBA Programming, Dedicated Software, Accounting, Living Skills ...

Tuesday, May 26, 2020

Searching for Data With a User Form in Excel Populated user form

Searching for Data With a User Form in Excel
Populated user form
To start, I've created some dummy data in a table
Table of dummy data for searching
The form obviously needs fields for each column so the basic form design looks like this

search Userform design
The 'Not found' is a label that will be used to indicate when a record isn't found. To start with this label is not visible. When a record isn't found the code just makes it visible.
The macro to load the form is run by clicking a shape in the worksheet.

Searching with the Form

With the userform displayed we can enter a number into the record field and click on Search.
searching for record with user form
The code now has to locate this number in the Record column of the table and then populate the form's fields with the data from that found record.
If the record number is not found, the 'Not found' error is displayed.

Download Sample Workbook

All the code in this post can be downloaded in this workbook.
Download the Excel Workbook. Note: This is a .xlsm file please ensure your browser doesn't change the file extension on download.
 

Form VBA for Searching

Using the Match function the code can locate the row within the table where the Record Number is.
The value entered into the form is a string so it must be cast to a Long using CLng(). I'm using structured references to search only the data in the Record column. The table is just called the default name, Table1.
If I'm looking for Record Number 47, which is the value in TextBox1, Match uses this to return the number of the table row where 47 is located.
VBA Match looking for data in table
I now know where the record is so I can set a range to the first cell of that record
Set range to first cell in table row

Error Handling

When the code searches for the record number an error can occur if that number is not found, so I turn off default error handling before doing this search.
Once the search if performed I can test if an error has occurred and display the 'Not found' error message.

Populating the Form With the Record's Data

Knowing the first cell of the record I can use Offset to read the values from each field and put them into the form.
VBA to populate the user form fields
Populated user form

Summary

This is a standalone piece of code for searching and can be adapted to many situations. Try integrating it with your own code or modify the user form code from my other blog posts.
Have a great day,

#evba #etipfree #eama #kingexcel
📤How to Download ebooks: https://www.evba.info/2020/02/instructions-for-downloading-documents.html?m=1

No comments:

Post a Comment