473,796 Members | 2,839 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Searching entire database for string

7 New Member
Hi, I am not a computer programmer. I have been learning VBA along the way of making this script. I know Access and SQL.

I have a very large database with many tables and queries. My goal is to write a script or function that will search the entire database for a certain string (actually two strings).

I have tried using a series of queries and unioning them together but this is a very scrappy way of doing this. Perhaps there is a method of automatically searching every field in every table for a string? I'm sure this has been done before but I have been searching the internet for about a week and have come up with nothing, so here I am, asking for help.

Any input is GREATLY appreciated; I am getting flustered due to my lack of knowledge with VBA!

Thanks!
Ian
Jul 16 '08 #1
9 16377
ADezii
8,834 Recognized Expert Expert
Just subscribing, when I get a chance I'll see what I can come up with.
Jul 17 '08 #2
Delerna
1,134 Recognized Expert Top Contributor
Hi, this is an extract from some code I had in an Access form
It should get you started

Expand|Select|Wrap|Line Numbers
  1. Private Sub cmdSearchTheTables_Click()
  2.     Dim DB As dao.Database
  3.     Dim tbl As dao.TableDef
  4.     Dim fld As dao.Field
  5.  
  6.     Set DB = CurrentDb
  7.     For Each tbl In DB.TableDefs
  8.         For Each fld In tbl.Fields
  9.             If fld.Value = "Search string" Then MsgBox "Found it" 
  10.         Next
  11.     Next
  12.     Set tbl = Nothing
  13.     Set fld = Nothing
  14.     Set DB = Nothing
  15. End Sub
  16.  
you will of course need a reference to "Microsoft DAO 3.6 object library"
Jul 17 '08 #3
ischwartz88
7 New Member
Ah! The code makes sense to me, and I have DAO 3.6 installed and enabled.

I have attached the code to a button called cmdSearchTheTab les.

However, it says the IF statement
Expand|Select|Wrap|Line Numbers
  1. If fld.Value Like "*MK 5*" Then
is an invalid operation.

I tried a few different syntax forms for the line, but it still returned the same error.

Am I missing something? Do I need to assign a text field to output the result into?
Jul 17 '08 #4
ischwartz88
7 New Member
OK. I have added much to the Sub. My code now reads as:
Expand|Select|Wrap|Line Numbers
  1.  
  2. Public Sub GenerateFieldSizeInfo()
  3.     Dim cdb As database
  4.     Dim oTable As TableDef
  5.     Dim oField As field
  6.     Dim rsTable As Recordset
  7.     Dim strSQLTable As String
  8.     Dim iMaxSize As Integer
  9.     Dim iHeadroom As Integer
  10.     Dim iFileNumber As Integer
  11.     Dim strOutputFile As String
  12.  
  13.     Dim ddb As database
  14.     Dim dtbl As TableDef
  15.     'Dim dfld As field
  16.  
  17.     'Create the header file. (If the file already exists, its contents are overwritten.)
  18.     iFileNumber = 1
  19.     strOutputFile = "C:\etc,etc."
  20.  
  21.     Open strOutputFile For Output As #iFileNumber
  22.     'Open the NWSS database.
  23.     Set cdb = CurrentDb
  24.  
  25.     Print #iFileNumber, " Table"; Tab(40); "Field"; Tab(70); "Relevant Text"; Tab(101); "Size"; Tab(111); "Max"; Tab(117); "Headroom"
  26.     Print #iFileNumber, String(125, "-")
  27.     For Each oTable In cdb.TableDefs
  28.       'If (StrComp("tbl", Left$(oTable.Name, 3)) = 0) Then
  29.         For Each oField In oTable.Fields
  30.           If (oField.Type = 10) Then
  31.             Print #iFileNumber, " "; oTable.Name;
  32.             Print #iFileNumber, Tab(40); oField.Name; Tab(104 - Len(Str(oField.Size))); oField.Size;
  33.             strSQLTable = "SELECT " + "[" + oField.Name + "]"
  34.             strSQLTable = strSQLTable + " FROM " + "[" + oTable.Name + "]"
  35.             strSQLTable = strSQLTable + " ORDER BY " + "[" + oField.Name + "]"
  36.             Set rsTable = cdb.OpenRecordset(strSQLTable, dbOpenDynaset)
  37.             If Not rsTable.EOF Then
  38.               rsTable.MoveFirst
  39.             End If
  40.             Do Until rsTable.EOF
  41.               If oField.Value Like "*Search text*" Then
  42.                 Print #iFileNumber, Tab(70 - Len(Str(oField))); oField
  43.               End If
  44.               rsTable.MoveNext
  45.             Loop
  46.             iMaxSize = 0
  47.             Do Until rsTable.EOF
  48.               If (Len(rsTable.Fields(0).Value) > iMaxSize) Then
  49.                 iMaxSize = Len(rsTable.Fields(0).Value)
  50.               End If
  51.               rsTable.MoveNext
  52.             Loop
  53.             iHeadroom = oField.Size - iMaxSize
  54.             Print #iFileNumber, Tab(114 - Len(Str(iMaxSize))); iMaxSize;
  55.             Print #iFileNumber, Tab(124 - Len(Str(iHeadroom))); iHeadroom
  56.             rsTable.Close
  57.           End If
  58.         Next
  59.           Print #iFileNumber, ""
  60.       'End If
  61.     Next
  62.     Close #iFileNumber
  63. End Sub
  64.  
I am still getting the "run-time error '3219', invalid operation" message when I try to run the script. It pertains to the IF statement in line 40. Anyone have any suggestions? I am puzzled because this should work!
Jul 17 '08 #5
missinglinq
3,532 Recognized Expert Specialist
Just out of curiosity's sake, in what real-world situation would you need to search every field of every table for a given search string?

Welcome to Bytes!

Linq ;0)>
Jul 17 '08 #6
ischwartz88
7 New Member
Just out of curiosity's sake, in what real-world situation would you need to search every field of every table for a given search string?

Welcome to Bytes!

Linq ;0)>
This is a task given to me for my job. It is to find data sensitive to a certain location. The script will be able to be used on any database made in the future; henceforth, creating a script to search every field is the most efficient way to go about this.

After the script is fully functional on VBA, I plan to translate it into VB and have it read a given database which is inputted by the user.
Jul 17 '08 #7
Delerna
1,134 Recognized Expert Top Contributor
hmmmm
the function LIKE compares two strings.
Maybe its having a problem with one of them being a field object.
Try
Expand|Select|Wrap|Line Numbers
  1. Dim str as string
  2. str=fld.value
  3. if str like "*MK 5*" Then
  4.  
Jul 17 '08 #8
ADezii
8,834 Recognized Expert Expert
I've written an Algorithm for you that will search every Field in every Table for a Search String that you specify. System Tables, those prefaced with 'MSys' or 'USys', are ignored. If a match(es) are found, the Record Number, Table Name, Field Name, and the actual Field Value containing the String are written to the Immediate Window. The Function will return True if successful, otherwise False. The code is very flexible in that the results can easily be saved to a Table, written to a List Box, printed to a Text File, etc. with little modification. You can simply call the Function within an Expression passing it the required Search String, then test for success. I did my testing on all the Tables of the Northwind Database, looking for the String 'Seafood'. For testing purposes, I added this String to several Fields, in multiple Tables. The Function Call and subsequent results are posted below:
Expand|Select|Wrap|Line Numbers
  1. Public Function fSearchForString(strSearchString) As Boolean
  2. On Error GoTo Err_fSearchForString
  3.  
  4. Dim tdf As DAO.TableDef
  5. Dim MyDB As Database
  6. Dim MyRS As Recordset
  7. Dim intNumOfFields As Integer
  8. Dim intCounter As Integer
  9.  
  10. 'Let's not get ridiculous, need at least 4 Characters
  11. If Len(strSearchString) <= 3 Then Exit Function
  12.  
  13. Set MyDB = CurrentDb
  14.  
  15. DoCmd.Hourglass True
  16.  
  17. Debug.Print "The String [" & strSearchString & "] has been found in the following locations:"
  18. Debug.Print "******************************************************************************************"
  19. Debug.Print
  20.  
  21. For Each tdf In CurrentDb.TableDefs
  22.   If Not tdf.Name Like "MSys*" Or Not tdf.Name Like "MSys*" Then    'ignore System Tables
  23.     Set MyRS = MyDB.OpenRecordset(tdf.Name, dbOpenDynaset)
  24.       intNumOfFields = MyRS.Fields.Count
  25.         For intCounter = 0 To intNumOfFields - 1
  26.           Do While Not MyRS.EOF
  27.             If InStr(MyRS.Fields(intCounter).Value, strSearchString) > 0 Then
  28.               Debug.Print "Rec Num: " & MyRS.AbsolutePosition + 1 & " | " & _
  29.                           "Table: " & tdf.Name & " | " & "Field: " & _
  30.                            MyRS.Fields(intCounter).Name & " | Value: " & _
  31.                            MyRS.Fields(intCounter).Value
  32.             End If
  33.             MyRS.MoveNext
  34.           Loop
  35.           MyRS.MoveFirst
  36.         Next
  37.   End If
  38. Next
  39.  
  40. DoCmd.Hourglass False
  41.  
  42. MyRS.Close
  43. Set MyRS = Nothing
  44.  
  45. fSearchForString = True
  46.  
  47. Exit_fSearchForString:
  48.   Exit Function
  49.  
  50. Err_fSearchForString:
  51.   fSearchForString = False
  52.   MsgBox Err.Description, vbExclamation, "Error in fSearchForString()"
  53.   DoCmd.Hourglass False
  54.   If Not MyRS Is Nothing Then
  55.     MyRS.Close
  56.     Set MyRS = Nothing
  57.   End If
  58.     Resume Exit_fSearchForString
  59. End Function
Call to Function:
Expand|Select|Wrap|Line Numbers
  1. If fSearchForString("Seafood") Then
  2.   MsgBox "Search  for String a success!", vbExclamation, "Success"
  3. Else
  4.   MsgBox "What in the world have you done, ADezii!", vbCritical, "Failure"
  5. End If
Sample OUTPUT:
Expand|Select|Wrap|Line Numbers
  1. The String [Seafood] has been found in the following locations:
  2. ******************************************************************************************
  3.  
  4. Rec Num: 8 | Table: Categories | Field: CategoryName | Value: Seafood
  5. Rec Num: 12 | Table: Employees | Field: LastName | Value: Seafood
  6. Rec Num: 5 | Table: Employees | Field: Title | Value: Sales Seafood Manager
  7. Rec Num: 1 | Table: Products | Field: ProductName | Value: Chai Seafood
  8. Rec Num: 23 | Table: Products | Field: ProductName | Value: Tunnbröd Seafood
  9. Rec Num: 37 | Table: Products | Field: ProductName | Value: Seafood Gravad lax
  10. Rec Num: 4 | Table: Shippers | Field: CompanyName | Value: Seafood Express
  11. Rec Num: 19 | Table: Suppliers | Field: CompanyName | Value: New England Seafood Cannery
Jul 17 '08 #9
ischwartz88
7 New Member
Perfect! Thank you very much. I played around with the code for a bit and I ended up combining my script with yours, and it works perfectly!
Jul 22 '08 #10

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

Similar topics

4
2767
by: Michi | last post by:
I was wondering what the best solution is for making large numbers of TEXT (or BLOB?) fields searchable. For example, if I have a forum, what is the best way to be able to search for specific words? How about exact phrases? I saw a solution where all words are preindexed in a "dictionary" like table and then another table stores the word matches. That seems really fast, but it has two major problems: 1) it can't do exact matches, and 2)...
3
2093
by: Paul H | last post by:
I have a text file that contains the following: ******************** __StartCustomerID_41 Name: Fred Smith Address: 57 Pew Road Croydon
7
2207
by: junky_fellow | last post by:
Can anyone suggest some efficient way to search a substring in a text file. For eg. suppose i want to search the pattern "abc" in a text file, then which algorithm should i use. I just want some hints, not the complete program. thanx in advance.....
33
2517
by: Geoff Jones | last post by:
Hiya I have a DataTable containing thousands of records. Each record has a primary key field called "ID" and another field called "PRODUCT" I want to retrieve the rows that satisy the following criteria: I have a list of about 100 numbers which correspond to the ID field and also another 40 say numbers corresponding to the numbers in the PRODUCT field. I want to show the rows that correspond to both these criteria.
1
2903
by: Jon Beverley | last post by:
I am looking for some assistance with searching a third part LDAP database. I have managed to read from it and write to it using Dim objAD As ActiveDs.IADs Dim objDS As ActiveDs.IADsOpenDSObject Dim objContainer As ActiveDs.IADsContainer Dim strUser As String
1
1542
by: thehumantrashcan | last post by:
Hi, This is the first database I have ever created, so please bear with me. I've created a simple database with 1 column and about 80,000 rows. In each row is a word (basically a dictionary without definitions). I have written a query which works, and is, as follows (you'll notice that i'm not the most original of people) SELECT word
4
5350
by: Hunk | last post by:
Hi I have a binary file which contains records sorted by Identifiers which are strings. The Identifiers are stored in ascending order. I would have to write a routine to give the record given the Identifier. The logical way would be to read the record once and put it in an STL container such as vector and then use lower_bound to search for a given identifier. But for some strange reason i'm asked to not use a container but instead...
2
2078
by: neilio2j | last post by:
hi, can anyone tell me how to search a given directory using C++? so far i have been successful in searching a file named, for tags"h:\\tags.cpp", whereas i would like to search for all files in the entire h: directory. this is the code i have used for searching the file named, "h:\\tags.cpp", /*char filename; cout<<"Please enter the filename";
0
1448
by: Kassimu | last post by:
Hi guys out there, There is this database Iam creating, I have a table with 40 fields among which there are Date/time, Text, Number, Memo and Yes/No fields and I have created the form bound to that tabe. I have also created Unbound form (for searching purpose) which is similar in layout with the bound one; in this search form the user will fill-in the keywords in as many text boxes as he wish to narrow down the search. The search results are...
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
9525
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
10452
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
10169
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
9050
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
5440
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4115
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.