Checking for Existing Field in Table

  • Thread starter RedHeadedMonster via AccessMonster.com
  • Start date
R

RedHeadedMonster via AccessMonster.com

Ok I have the following code:

Function CheckIfFieldExist(TableName As String, FieldName As String) As
Boolean
On Error GoTo CheckIfFieldExist_Err
' Function that check if a field exist in the table
' Return True if exist , and False if doesn't exist
Dim I As String
CheckIfFieldExist = True
I = Application.CurrentDb.TableDefs(TableName).Fields(FieldName).Name
Exit Function
CheckIfFieldExist_Err:
If Err = 3265 Then
CheckIfFieldExist = False
Else
MsgBox Error
End If

End Function

this is the other half of the code:

'Late

If CheckIfFieldExist("tblCDRLMetricsFinal2", "Late") Then
' Exist
Else
' Doesn't Exist

Dim dbCurLate As Database
Dim tdfLate As TableDef
Dim fldLate As Field

Set dbCurLate = CurrentDb()
Set tdfLate = dbCurLate.TableDefs("tblCDRLMetrics2Final")
Set fldLate = tdfLate.CreateField("Late", dbInteger)

tdfLate.Fields.Append fldLate
tdfLate.Fields.Refresh
End If

Problem is....regardless or whether or not "Late" exists (True or False The
code tries to create the "Late" field...of course if its already there I get
an error message. I dont want it to try and create if its there....I've
looked at this code until Im crosseyed...Someone see what the hell Im doing
wrong?
Thanx!
RHM
 
D

Daniel Pineault

A couple things come to mind.

1. I never set a function to True as the default and then switch it to
false. I always do the inverse to avoid false positives. Below is what I
would do:

Function CheckIfFieldExist(TableName As String, FieldName As String) As
Boolean
' Function that check if a field exist in the table
' Return True if exist , and False if doesn't exist
Dim I As String

On Error GoTo Error_Handler

CheckIfFieldExist = False
I = Application.CurrentDb.TableDefs(TableName).Fields(FieldName).Name
CheckIfFieldExist = True 'If we made it to hear without triggering an
'error all is good

Error_Handler_Exit:
On Error Resume Next
Exit Function

Error_Handler:
If Err = 3265 Then 'Field not found in the specified table
Else
MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf
& "Error Number: " & _
Err.Number & vbCrLf & "Error Source: CheckIfFieldExist" & vbCrLf &
"Error Description: " & _
Err.Description, vbCritical, "An Error has Occured!"
End If
Resume Error_Handler_Exit
End Function


Sub AddField2Tbl(TableName As String)
Dim dbCurLate As Database
Dim tdfLate As TableDef
Dim fldLate As Field

On Error GoTo Error_Handler

If CheckIfFieldExist(TableName, "Late") = True Then
' Exist
Else
' Doesn't Exist

Set dbCurLate = CurrentDb()
Set tdfLate = dbCurLate.TableDefs(TableName)
Set fldLate = tdfLate.CreateField("Late", dbInteger)

tdfLate.Fields.Append fldLate
tdfLate.Fields.Refresh
End If

Error_Handler_Exit:
On Error Resume Next
Set fldLate = Nothing
Set tdfLate = Nothing
Set dbCurLate = Nothing
Exit Sub

Error_Handler:
MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf &
"Error Number: " & _
Err.Number & vbCrLf & "Error Source: AddField2Tbl" & vbCrLf & "Error
Description: " & _
Err.Description, vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit
End Sub



2. Another method would be to simply add the field without testing and
simply trap the error that arises if the field already exists.
--
Hope this helps,

Daniel Pineault
http://www.cardaconsultants.com/
For Access Tips and Examples: http://www.devhut.net
Please rate this post using the vote buttons if it was helpful.
 
J

Jeff Boyce

If you are trying to insert a new field in an Access table, what safeguards
do you have to ensure that the new field actually BELONGS in that table?
That is, if you want to get the best use of Access' relationally-oriented
features/functions, you need to "feed" it well-normalized data. How are you
ensuring that the new field "fits" the table?

Regards

Jeff Boyce
Microsoft Access MVP

--
Disclaimer: This author may have received products and services mentioned
in this post. Mention and/or description of a product or service herein
does not constitute endorsement thereof.

Any code or pseudocode included in this post is offered "as is", with no
guarantee as to suitability.

You can thank the FTC of the USA for making this disclaimer
possible/necessary.
 
R

RedHeadedMonster via AccessMonster.com

Thanks....but even with your mods its still doing exactly the same thing.
Trying to add the field whether its there or not (TRUE or FALSE) and hanging
A couple things come to mind.

1. I never set a function to True as the default and then switch it to
false. I always do the inverse to avoid false positives. Below is what I
would do:

Function CheckIfFieldExist(TableName As String, FieldName As String) As
Boolean
' Function that check if a field exist in the table
' Return True if exist , and False if doesn't exist
Dim I As String

On Error GoTo Error_Handler

CheckIfFieldExist = False
I = Application.CurrentDb.TableDefs(TableName).Fields(FieldName).Name
CheckIfFieldExist = True 'If we made it to hear without triggering an
'error all is good

Error_Handler_Exit:
On Error Resume Next
Exit Function

Error_Handler:
If Err = 3265 Then 'Field not found in the specified table
Else
MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf
& "Error Number: " & _
Err.Number & vbCrLf & "Error Source: CheckIfFieldExist" & vbCrLf &
"Error Description: " & _
Err.Description, vbCritical, "An Error has Occured!"
End If
Resume Error_Handler_Exit
End Function

Sub AddField2Tbl(TableName As String)
Dim dbCurLate As Database
Dim tdfLate As TableDef
Dim fldLate As Field

On Error GoTo Error_Handler

If CheckIfFieldExist(TableName, "Late") = True Then
' Exist
Else
' Doesn't Exist

Set dbCurLate = CurrentDb()
Set tdfLate = dbCurLate.TableDefs(TableName)
Set fldLate = tdfLate.CreateField("Late", dbInteger)

tdfLate.Fields.Append fldLate
tdfLate.Fields.Refresh
End If

Error_Handler_Exit:
On Error Resume Next
Set fldLate = Nothing
Set tdfLate = Nothing
Set dbCurLate = Nothing
Exit Sub

Error_Handler:
MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf &
"Error Number: " & _
Err.Number & vbCrLf & "Error Source: AddField2Tbl" & vbCrLf & "Error
Description: " & _
Err.Description, vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit
End Sub

2. Another method would be to simply add the field without testing and
simply trap the error that arises if the field already exists.
Ok I have the following code:
[quoted text clipped - 44 lines]
Thanx!
RHM
 
R

RedHeadedMonster via AccessMonster.com

Because the code only fires when it belongs in the table and isnt.

Jeff said:
If you are trying to insert a new field in an Access table, what safeguards
do you have to ensure that the new field actually BELONGS in that table?
That is, if you want to get the best use of Access' relationally-oriented
features/functions, you need to "feed" it well-normalized data. How are you
ensuring that the new field "fits" the table?

Regards

Jeff Boyce
Microsoft Access MVP
Ok I have the following code:
[quoted text clipped - 47 lines]
Thanx!
RHM
 
J

Jeff Boyce

Let me try stating my concern a different way...

How will your code prevent someone from adding a field to hold "My
Grandmother's Age" into a table of "Customers"?

Regards

Jeff Boyce
Microsoft Access MVP

--
Disclaimer: This author may have received products and services mentioned
in this post. Mention and/or description of a product or service herein
does not constitute endorsement thereof.

Any code or pseudocode included in this post is offered "as is", with no
guarantee as to suitability.

You can thank the FTC of the USA for making this disclaimer
possible/necessary.

RedHeadedMonster via AccessMonster.com said:
Because the code only fires when it belongs in the table and isnt.

Jeff said:
If you are trying to insert a new field in an Access table, what
safeguards
do you have to ensure that the new field actually BELONGS in that table?
That is, if you want to get the best use of Access' relationally-oriented
features/functions, you need to "feed" it well-normalized data. How are
you
ensuring that the new field "fits" the table?

Regards

Jeff Boyce
Microsoft Access MVP
Ok I have the following code:
[quoted text clipped - 47 lines]
Thanx!
RHM
 
D

Daniel Pineault

That's very odd because I tried it at my end and it works fine for me.

What error is raise?
--
Hope this helps,

Daniel Pineault
http://www.cardaconsultants.com/
For Access Tips and Examples: http://www.devhut.net
Please rate this post using the vote buttons if it was helpful.



RedHeadedMonster via AccessMonster.com said:
Thanks....but even with your mods its still doing exactly the same thing.
Trying to add the field whether its there or not (TRUE or FALSE) and hanging
A couple things come to mind.

1. I never set a function to True as the default and then switch it to
false. I always do the inverse to avoid false positives. Below is what I
would do:

Function CheckIfFieldExist(TableName As String, FieldName As String) As
Boolean
' Function that check if a field exist in the table
' Return True if exist , and False if doesn't exist
Dim I As String

On Error GoTo Error_Handler

CheckIfFieldExist = False
I = Application.CurrentDb.TableDefs(TableName).Fields(FieldName).Name
CheckIfFieldExist = True 'If we made it to hear without triggering an
'error all is good

Error_Handler_Exit:
On Error Resume Next
Exit Function

Error_Handler:
If Err = 3265 Then 'Field not found in the specified table
Else
MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf
& "Error Number: " & _
Err.Number & vbCrLf & "Error Source: CheckIfFieldExist" & vbCrLf &
"Error Description: " & _
Err.Description, vbCritical, "An Error has Occured!"
End If
Resume Error_Handler_Exit
End Function

Sub AddField2Tbl(TableName As String)
Dim dbCurLate As Database
Dim tdfLate As TableDef
Dim fldLate As Field

On Error GoTo Error_Handler

If CheckIfFieldExist(TableName, "Late") = True Then
' Exist
Else
' Doesn't Exist

Set dbCurLate = CurrentDb()
Set tdfLate = dbCurLate.TableDefs(TableName)
Set fldLate = tdfLate.CreateField("Late", dbInteger)

tdfLate.Fields.Append fldLate
tdfLate.Fields.Refresh
End If

Error_Handler_Exit:
On Error Resume Next
Set fldLate = Nothing
Set tdfLate = Nothing
Set dbCurLate = Nothing
Exit Sub

Error_Handler:
MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf &
"Error Number: " & _
Err.Number & vbCrLf & "Error Source: AddField2Tbl" & vbCrLf & "Error
Description: " & _
Err.Description, vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit
End Sub

2. Another method would be to simply add the field without testing and
simply trap the error that arises if the field already exists.
Ok I have the following code:
[quoted text clipped - 44 lines]
Thanx!
RHM

--



.
 
R

RedHeadedMonster via AccessMonster.com

Because the code only adds a field name of LATE to a specific table at a
specific request of a specific report, but only if its not there already.
They dont get to decide what table or what information only that they want to
see a report. They arent writing code, they arent editing information, they
aren't doing anything but selecting pre-ordained parameters to run a report.

All Im looking for is a second set of eyeballs hopefully picking up something
that I've done wrong in the code that Im not seeing because I've looked at it
all day, and so far it attempts to add Late if its not there and if it is
there, I just want it added if its not. So can you help with the problem or
not?

Thanx
RHM


Jeff said:
Let me try stating my concern a different way...

How will your code prevent someone from adding a field to hold "My
Grandmother's Age" into a table of "Customers"?

Regards

Jeff Boyce
Microsoft Access MVP
Because the code only fires when it belongs in the table and isnt.
[quoted text clipped - 16 lines]
 
R

RedHeadedMonster via AccessMonster.com

3191

Daniel said:
That's very odd because I tried it at my end and it works fine for me.

What error is raise?
Thanks....but even with your mods its still doing exactly the same thing.
Trying to add the field whether its there or not (TRUE or FALSE) and hanging
[quoted text clipped - 79 lines]
 
R

RedHeadedMonster via AccessMonster.com

3191: Can not define define field more than once
Because its trying to add it even tho its already there.
3191
That's very odd because I tried it at my end and it works fine for me.
[quoted text clipped - 4 lines]
 
J

John Spencer

Here is a different function that checks a different way. It is probably a
bit slower, but not noticeably on most computers unless your were doing this
in a loop for some reason and checking a very large number of tables and fields.

Function CheckIfFieldExists(strTableName As String, _
strFieldName As String) As Boolean
Dim tDef As TableDef
Dim db As DAO.Database
Dim tfTableCheck As Boolean, tfFieldCheck As Boolean
Dim fldAny As Field

Set db = CurrentDb()
'Make sure the table exists
For Each tDef In db.TableDefs
If tDef.Name = strTableName Then
'Now check for the field
tfTableCheck = True
For Each fldAny In tDef.Fields
If fldAny.Name = strFieldName Then
tfFieldCheck = True
Exit For
End If
Exit For
Next fldAny
End If
Next tDef

If tfTableCheck = False Then
'MsgBox "No such table"
CheckIfFieldExists = False
Else
CheckIfFieldExists = tfFieldCheck
End If

End Function


John Spencer
Access MVP 2002-2005, 2007-2010
The Hilltop Institute
University of Maryland Baltimore County
 
J

Jeff Boyce

Thanks for the clarification. I still don't understand the why well enough
to be able to help. Hopefully one of the other newsgroup readers can help.

It sounds like you're using this approach to work out a report ... if so, it
isn't necessary and is rarely a good idea to create a table in Access simply
to pull together the data for a report. In most instances, you can use
queries.

I've been trying to learn enough about your business need (not the technique
you propose) to see if there might be other options available to you.

Good luck!

Regards

Jeff Boyce
Microsoft Access MVP

--
Disclaimer: This author may have received products and services mentioned
in this post. Mention and/or description of a product or service herein
does not constitute endorsement thereof.

Any code or pseudocode included in this post is offered "as is", with no
guarantee as to suitability.

You can thank the FTC of the USA for making this disclaimer
possible/necessary.

RedHeadedMonster via AccessMonster.com said:
Because the code only adds a field name of LATE to a specific table at a
specific request of a specific report, but only if its not there already.
They dont get to decide what table or what information only that they want
to
see a report. They arent writing code, they arent editing information,
they
aren't doing anything but selecting pre-ordained parameters to run a
report.

All Im looking for is a second set of eyeballs hopefully picking up
something
that I've done wrong in the code that Im not seeing because I've looked at
it
all day, and so far it attempts to add Late if its not there and if it is
there, I just want it added if its not. So can you help with the problem
or
not?

Thanx
RHM


Jeff said:
Let me try stating my concern a different way...

How will your code prevent someone from adding a field to hold "My
Grandmother's Age" into a table of "Customers"?

Regards

Jeff Boyce
Microsoft Access MVP
Because the code only fires when it belongs in the table and isnt.
[quoted text clipped - 16 lines]
Thanx!
RHM
 
R

RedHeadedMonster via AccessMonster.com

Changed to this and still getting error 3191. So code still not recognizing
that field check = True.
Thanx for suggestion tho.

John said:
Here is a different function that checks a different way. It is probably a
bit slower, but not noticeably on most computers unless your were doing this
in a loop for some reason and checking a very large number of tables and fields.

Function CheckIfFieldExists(strTableName As String, _
strFieldName As String) As Boolean
Dim tDef As TableDef
Dim db As DAO.Database
Dim tfTableCheck As Boolean, tfFieldCheck As Boolean
Dim fldAny As Field

Set db = CurrentDb()
'Make sure the table exists
For Each tDef In db.TableDefs
If tDef.Name = strTableName Then
'Now check for the field
tfTableCheck = True
For Each fldAny In tDef.Fields
If fldAny.Name = strFieldName Then
tfFieldCheck = True
Exit For
End If
Exit For
Next fldAny
End If
Next tDef

If tfTableCheck = False Then
'MsgBox "No such table"
CheckIfFieldExists = False
Else
CheckIfFieldExists = tfFieldCheck
End If

End Function

John Spencer
Access MVP 2002-2005, 2007-2010
The Hilltop Institute
University of Maryland Baltimore County
Ok I have the following code:
[quoted text clipped - 44 lines]
Thanx!
RHM
 
R

RedHeadedMonster via AccessMonster.com

Yes definitely using approach to work out report.
How would you do it with a query?

Jeff said:
Thanks for the clarification. I still don't understand the why well enough
to be able to help. Hopefully one of the other newsgroup readers can help.

It sounds like you're using this approach to work out a report ... if so, it
isn't necessary and is rarely a good idea to create a table in Access simply
to pull together the data for a report. In most instances, you can use
queries.

I've been trying to learn enough about your business need (not the technique
you propose) to see if there might be other options available to you.

Good luck!

Regards

Jeff Boyce
Microsoft Access MVP
Because the code only adds a field name of LATE to a specific table at a
specific request of a specific report, but only if its not there already.
[quoted text clipped - 32 lines]
 
J

John Spencer

The function works for me. I tested it with a bad tablename and a bad field
name in an existing table and with valid table and field names. It only
returned true in the last case.

You can test to see if the function is working by using the VBA immediate
window and entering
?CheckIfFieldExists("SomeTable","SomeField")
and varying the validity of the table and field names you are passing

I am going to guess that something may have corrupted your database or that
something in your calling function is wrong
If CheckIfFieldExists("tblCDRLMetricsFinal2", "Late")=True Then
' Exists
Else
...
End If

If corruption in the VBA code is the problem, you can try the following from
Allen Browne.

Here is a standard sequence to try to rescue a corrupted mdb

0. Make a backup copy of the file.
00. Make a backup copy of the file.

1. Uncheck the boxes under:
Tools | Options | General | Name AutoCorrect
Explanation of why: http://allenbrowne.com/bug-03.html

2. Compact the database to get rid of this junk:
Tools | Database Utilities | Compact

3. Close Access. Make a backup copy of the file.
Decompile the database by entering something like this at the command
prompt while Access is not running. It is all one line, and includes the quotes:
"c:\Program Files\Microsoft office\office\msaccess.exe" /decompile
"c:\MyPath\MyDatabase.mdb"

4. Open Access, and compact again.

5. Open a code window.
Choose References from the Tools menu.
Uncheck any references you do not need.
For a list of the ones you typically need in your version of Access, see:
http://allenbrowne.com/ser-38.html

6. Still in the code window, choose Compile from the Debug menu.
Fix any errors, and repeat until it compiles okay.

At this point, you should have a database where the name-autocorrect errors
are gone, the indexes are repaired, inconsistencies between the text- and
compiled-versions of the code are fixed, and reference ambiguities are resolved.

If it is still a problem, the next step would be to get Access to rebuild the
database for you. Follow the steps for the first symptom in this article:
Recovering from Corruption
at:
http://allenbrowne.com/ser-47.html

--
Allen Browne - Microsoft MVP. Perth, Western Australia.
Reply to group,
rather than allenbrowne at mvps dot org.


John Spencer
Access MVP 2002-2005, 2007-2010
The Hilltop Institute
University of Maryland Baltimore County
Changed to this and still getting error 3191. So code still not recognizing
that field check = True.
Thanx for suggestion tho.

John said:
Here is a different function that checks a different way. It is probably a
bit slower, but not noticeably on most computers unless your were doing this
in a loop for some reason and checking a very large number of tables and fields.

Function CheckIfFieldExists(strTableName As String, _
strFieldName As String) As Boolean
Dim tDef As TableDef
Dim db As DAO.Database
Dim tfTableCheck As Boolean, tfFieldCheck As Boolean
Dim fldAny As Field

Set db = CurrentDb()
'Make sure the table exists
For Each tDef In db.TableDefs
If tDef.Name = strTableName Then
'Now check for the field
tfTableCheck = True
For Each fldAny In tDef.Fields
If fldAny.Name = strFieldName Then
tfFieldCheck = True
Exit For
End If
Exit For
Next fldAny
End If
Next tDef

If tfTableCheck = False Then
'MsgBox "No such table"
CheckIfFieldExists = False
Else
CheckIfFieldExists = tfFieldCheck
End If

End Function

John Spencer
Access MVP 2002-2005, 2007-2010
The Hilltop Institute
University of Maryland Baltimore County
Ok I have the following code:
[quoted text clipped - 44 lines]
Thanx!
RHM
 
J

Jeff Boyce

How depends on what. What data structure do you have? Knowing that would
provide folks here a way to offer suggestions on using queries.

As a general approach, you may find it much more flexible (and much less
work) to use queries as your sources for your reports.

Regards

Jeff Boyce
Microsoft Access MVP

--
Disclaimer: This author may have received products and services mentioned
in this post. Mention and/or description of a product or service herein
does not constitute endorsement thereof.

Any code or pseudocode included in this post is offered "as is", with no
guarantee as to suitability.

You can thank the FTC of the USA for making this disclaimer
possible/necessary.


RedHeadedMonster via AccessMonster.com said:
Yes definitely using approach to work out report.
How would you do it with a query?

Jeff said:
Thanks for the clarification. I still don't understand the why well
enough
to be able to help. Hopefully one of the other newsgroup readers can
help.

It sounds like you're using this approach to work out a report ... if so,
it
isn't necessary and is rarely a good idea to create a table in Access
simply
to pull together the data for a report. In most instances, you can use
queries.

I've been trying to learn enough about your business need (not the
technique
you propose) to see if there might be other options available to you.

Good luck!

Regards

Jeff Boyce
Microsoft Access MVP
Because the code only adds a field name of LATE to a specific table at a
specific request of a specific report, but only if its not there
already.
[quoted text clipped - 32 lines]
Thanx!
RHM
 
D

DrGUI

This is using ADO:

Private Function Check4Field(strTableName As String)

Dim fldName As Variant
Dim bFieldExists As Boolean
Dim rs As New ADODB.Recordset

rs.Open strTableName, CurrentProject.Connection

bFieldExists = False
For Each fldName In rs.Fields
'Debug.Print fldName.Name
If fldName.Name = "late" Then
bFieldExists = True
Exit For
End If
Next fldName
rs.Close
Set rs = Nothing

Check4Field = "Field 'Late' does not exist."
If bFieldExists Then Check4Field = "Field 'Late' exists."

End Function
 
R

RedHeadedMonster via AccessMonster.com

I always use queries as the source for my reports. This one was special case
because it involved using several parameters that the user could apply to
data that was being used by a crosstab query. It was just easier to create a
temporary table to hold the special request and then run the crosstab. You
probably know how persnickety crosstabs are. Anyway, it got it to work...and
its working wonderfully.

Jeff said:
How depends on what. What data structure do you have? Knowing that would
provide folks here a way to offer suggestions on using queries.

As a general approach, you may find it much more flexible (and much less
work) to use queries as your sources for your reports.

Regards

Jeff Boyce
Microsoft Access MVP
Yes definitely using approach to work out report.
How would you do it with a query?
[quoted text clipped - 28 lines]
 
R

RedHeadedMonster via AccessMonster.com

Finally got it to work, i went with checking for the existance of the field
and trapping for the error. Works like a charm.
Thanks for your time and your suggestions.
Have a Nice Day!
RHM

John said:
Here is a different function that checks a different way. It is probably a
bit slower, but not noticeably on most computers unless your were doing this
in a loop for some reason and checking a very large number of tables and fields.

Function CheckIfFieldExists(strTableName As String, _
strFieldName As String) As Boolean
Dim tDef As TableDef
Dim db As DAO.Database
Dim tfTableCheck As Boolean, tfFieldCheck As Boolean
Dim fldAny As Field

Set db = CurrentDb()
'Make sure the table exists
For Each tDef In db.TableDefs
If tDef.Name = strTableName Then
'Now check for the field
tfTableCheck = True
For Each fldAny In tDef.Fields
If fldAny.Name = strFieldName Then
tfFieldCheck = True
Exit For
End If
Exit For
Next fldAny
End If
Next tDef

If tfTableCheck = False Then
'MsgBox "No such table"
CheckIfFieldExists = False
Else
CheckIfFieldExists = tfFieldCheck
End If

End Function

John Spencer
Access MVP 2002-2005, 2007-2010
The Hilltop Institute
University of Maryland Baltimore County
Ok I have the following code:
[quoted text clipped - 44 lines]
Thanx!
RHM
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top