Question

I'm a newbie to VB and Access, so don't beat me up too much on this one :-P I am trying to take a value from an unbound text box and search the database (Access 2010) for a table name that matches the value. The tricky part is that the value is entered in the text box as ABC-123. I am using the mid(Me.Text... to split the value into two parts. The ABC is a prefix that is also in a table name called ABC-Tools. This prefix changes (MTE, MOLD, MFG, etc.) depending on the required entry. But I seem to keep getting stuck at how to use in the entire function the table name. Once I get that, then I want to take it a step further and go into the table and compare the next part of the textbox entry, the 123 section which is an asset number (auto-generated primary key within the table). I have tried using the DLookup but I ran into the same problem there. FYI, this is a homegrown Calibration Management Database for a company, and this code is within a "Record Data" button on a form. All text boxes are unbound and also export their contents to a pre-formatted Excel spreadsheet for record keeping.

Here is my code so far. Maybe I am WAY off on how to properly do this. Let me know if you need more information.

Cat = Mid(Me.Text4.Value, 1, InStr(Me.Text4.Value, "-") - 1) 'Takes data on the left of the "-" within unbound text4 box for tool asset prefix (eg. MOLD-xxx)

AssetNum = Mid(Me.Text4.Value, InStr(Me.Text4.Value, "-") + 1) 'Takes data on the right of the "-" within unbound text4 box for tool asset number (eg. xxxx-001)

'Check database for tool

If "& Cat &-Tools" <> "{look_for_table_matching & Cat &-Tools}" Then

msg = _
  MsgBox("Tool " & Cat & "-" & AssetNum & " does not exist. Please check that the tool is in the         database and retry.", _
    vbExclamation, "")

Else {continue on with the rest of the script}

End If
Was it helpful?

Solution

To search through the list of tables in the DB:

Dim tdf as TableDef
Dim MatchingTable as String

For each tdf in CurrentDB.TableDefs
   If tdf.Name Like Cat & "*" Then
      MatchingTable = tdf.Name
      Exit For
   End If
Next

If MatchingTable = "" Then 'table not found
   Msgbox...
End If

To then search the table:

'Dlookup returns a null value if nothing found
str = Nz(Dlookup("<Name of field>",MatchingTable,"AssetNumber = " & AssetNum),"")

If str = "" Then 'asset num not found
   Msgbox...
End If
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top