What is the correct Access DDL query to add a Boolean datatype column to a table?
So far I've seen examples like the following...
ALTER TABLE MyTable ADD MyNewColumName BIT
but they do not seem to be 100% correct since
Access does not apply the checkbox control to the newly added column, and
the allowed values for that column seem to be 0 and -1
In access the Yes/No data type is a logical field that can display yes/no, true/false, or on/off. When you look at VBA code the true and false constants are equivalent to -1 and 0.
If you use this field to populate a check box it will function properly.
You may be able to Change your alter statement to use "YESNO" as such:
ALTER TABLE mytable ADD mynewcolumn YESNO
That should give you the desired check box in the access table column.
A DAO example.
''Requires reference to Microsoft DAO 3.6 Object Library
Dim tdf As DAO.TableDef
Dim fld As DAO.Field
Dim db As Database
Dim strSQL As String
Set db = CurrentDb
''Create a table ...
strSQL = "Create Table tblLTD (TheYesNoCheck YesNo, TheYesNoCombo YesNo)"
db.Execute strSQL
''It is now in the table collection, so ...
Set tdf = db.TableDefs("tblLTD")
''Change the way the YesNo fields display.
''A Checkbox
Set fld = tdf.Fields("TheYesNoCheck")
Set prp = fld.CreateProperty("DisplayControl", dbInteger, acCheckBox)
fld.Properties.Append prp
''A combobox
Set fld = tdf.Fields("TheYesNoCombo")
Set prp = fld.CreateProperty("DisplayControl", dbInteger, acComboBox)
fld.Properties.Append prp
''We will need a format
Set prp = fld.CreateProperty("Format", dbText, "Yes/No")
fld.Properties.Append prp
From: http://wiki.lessthandot.com/index.php/Add_a_Display_Control_(Checkbox,_Combobox)_to_a_YesNo_Field
Related
This is what I have so far with some extraneous code left out and some anonymous database and variable names:
Dim dB as DAO.Database
Dim tdf as DAO.TableDef
Dim newField As DAO.Field
Dim newFieldNameVar As String
newFieldNameVar = "Variable Name"
Set dB = CurrentDb
Set tdf = dB.TableDefs("PreExistingTable")
Set newField = tdf.CreateField(newFieldNameVar)
tdf.Fields.Append newField
Set newField = Nothing
Set tdf = Nothing
Set dB = Nothing
Where the aforementioned code exists in my function is not in a loop but the newFieldNameVar is a product of a loop, and so changes regularly based on question thread irrelevant conditions.
At the point the .Fields.Append line executes I get this run-time error: Invalid field data type. '3259' I am fairly new to programming in any form or fashion, but imagine that I might be using the wrong syntax for the variable used as the Name element of the .CreateField Method. Any ideas? Am I able to use a string variable as the Name in the .CreateField Method?
Thanks for the help in advance!
While Type is an optional parameter of the .CreateField method, each field does need a type before you can append it to the table, else Access will throw this error.
It's also a good practice to specify field size.
Specify your field type, e.g.:
Dim dB as DAO.Database
Dim tdf as DAO.TableDef
Dim newField As DAO.Field
Dim newFieldNameVar As String
newFieldNameVar = "Variable Name"
Set dB = CurrentDb
Set tdf = dB.TableDefs("PreExistingTable")
Set newField = tdf.CreateField(newFieldNameVar, dbText, 255) '255 character long text field
tdf.Fields.Append newField
Set newField = Nothing
Set tdf = Nothing
Set dB = Nothing
How can I iterate a record set that returns a field of type field2?
Is there a way to tell how many objects are in the field2 type?
Let me describe the relevant aspects of my table:
The table fields has field NMR which contains a list of possible options a user can select in another table. In the Experiments table, the field NMR is a combobox with populates the options from the other table.
The way I do this is in the Experiments table design, I have set the field this way:
Now in one of my forms, I need to read the value in Experiments!NMR which can be a multiple selections allowed combobox. The recordset rs!NMR is of type Field2.
To get the values, you iterate using an integer (i.e. rs!NMR(0) would return the first selected option). The problem is I don't know how to get the field count and calling !NMR(i) where i is greater than the number of elements will invoke a Run time error '3265', Object doesn't exist in this collection.
Their exist a size method only returns the field width size (4?) and the documentation states this is the size of the data type within the field2 object.
There doesn't seem to be a count method associated with field2 as using !NMR.Count invokes runtime error 438, Object doesn't support this method.
Code:
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim qry As String
qry = "SELECT * FROM Experiments"
Set db = CurrentDb
Set rs = db.OpenRecordset(qry, dbOpenSnapshot)
With rs
Do While Not .EOF
Dim i As Integer
For i = 0 to !NMR.Count ' or SOMETHING - this is the problem
' this is irrelevant, I need to know how to iterate the list
Next i
.MoveNext
Loop
End With
rs.Close
db.Close
Set rs = Nothing
Set db = Nothing
I've also tried logic control such as
Do While(!NMR(i) <> vbNullString) since the individual components are strings, but no luck. This issues the same 3265: Item isn't found error. Same for a loop with this check Do While Not IsNull(!NMR(i))
Is there a way to tell how many objects are in the Field !NMR?
You need to assign the complex Field2 to a Recordset2 object and loop through it.
Sub Whatever()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim rsComplex As DAO.Recordset2
Dim qry As String
qry = "SELECT * FROM Experiments"
Set db = CurrentDb
Set rs = db.OpenRecordset(qry, dbOpenSnapshot)
Do While Not rs.EOF
Set rsComplex = rs("NMR").Value
rsComplex.MoveLast
rsComplex.MoveFirst
Dim i As Integer
For i = 0 To rsComplex.RecordCount - 1 ' Asker modified
Debug.Print rsComplex(0)
rsComplex.MoveNext
Next i
rsComplex.Close
Set rsComplex = Nothing
rs.MoveNext
Loop
rs.Close
db.Close
Set rs = Nothing
Set db = Nothing
End Sub
I have an Access database with nearly 200 tables each with about 150 field. I need to change most of the field names and am writing some VBA code to programatically update the names to what I assign. The problem is that not all tables have exactly the same fields (some fields are missing from certain tables). Is there a way that I can write the change in the code, but just skip the change for a particular field if it doesn't exist in a particular table?
The basic code that I am using comes from this site: http://windowssecrets.com/forums/showthread.php/125845-Change-Field-name-in-Table-with-VBA
And here is my actual code. I'm brand new to VBA, so please be gentle.
Option Compare Database
Option Explicit
Public Sub changeFieldName()
Dim db As DAO.Database
Dim table As DAO.TableDef
Set db = CurrentDb
For
Set table = db.TableDefs("table")
table.Fields("Field1").Name = "name1"
table.Fields("Field2").Name = "name2"
if(IsNull(table.Fields("FieldDoesn'tExist").Name = "name")) Then End If
Set table = Nothing
Next
db.Close
Set db = Nothing
MsgBox "Changed"
End Sub
The "Then End If" statement doesn't work, but I don't know what to use here
Thanks for any help!
Paul
The way I'd approach it would be to put the old and new names into their own table named [NameMap]:
oldName newName
-------- --------
oldName1 newName1
oldName2 newName2
and then loop through that list to apply the name changes. The On Error Resume Next statement would allow the routine to continue if the table did not have a field whose name corresponded to one of the [oldName] values
Option Compare Database
Option Explicit
Public Sub changeFieldNames()
Dim cdb As DAO.Database, rst As DAO.Recordset, tbd As DAO.TableDef
Set cdb = CurrentDb
Set tbd = cdb.TableDefs("SampleTable")
Set rst = cdb.OpenRecordset("SELECT oldName, newName FROM NameMap", dbOpenSnapshot)
Do Until rst.EOF
On Error Resume Next
tbd.Fields(rst!oldName).Name = rst!newName
On Error GoTo 0
rst.MoveNext
Loop
rst.Close
Set rst = Nothing
Set tbd = Nothing
Set cdb = Nothing
End Sub
When importing the excel to access 2007, some date field had become text field. so i want to run query in access to change those columns data type to datetime. How can i pass the date format ("dd-mmm-yyyy") in sql ?
ALTER TABLE Tbl1
ALTER COLUMN [ABC] datetime
Thanks
Joe
If you have imported a column (field) from Excel and it has ended up in text format, you should be very wary of simply switching to a date time format. Access should already have interpreted the field as DateTime if it did not see it as mixed data type. You should create a new DateTime column and update it with the year month and day in an unambiguous format.
Let us say your column is mm/dd/yyyy, one option would be:
UPDATE Table SET NewDateTime = Right(DT,4) & "/" & Left(DT,2) & "/" & Mid(DT,4,2)
WHERE DT Like "##/##/####"
You cannot set the Format property with DDL and it is of no relevance outside MS Access. In general, I recommend that you do not use the Format property in tables, it is best controlled in forms and reports. Setting a format will inevitably confuse someone at some stage when a query does not work in the expected way.
If you really must set a format, you must use VBA, DAO and the TableDef.
Dim db As Database
Dim tdf As TableDef
Dim fld As DAO.Field
Dim prp As Property
Dim prpName As String
Dim prpValue As String
Dim prpType As Long
Set db = CurrentDb
Set tdf = db.TableDefs("Table1")
Set fld = tdf.Fields("ADate")
prpName = "Format"
prpValue = "yyyy/mm/dd"
prpType = dbText
On Error Resume Next
fld.Properties(prpName) = prpValue
If Err.Number = 3270 Then
Set prp = fld.CreateProperty(prpName, prpType, prpValue)
Err.Clear
fld.Properties.Append prp
End If
Debug.Print fld.Properties("Format")
Use cDate
cDate(rst.fields("fieldname"))
That should fix your issue.
I know I'm over thinking this, but I want to check a single value/field within a single record. For instance, I want to know if the value of the "closedDate" field in the record with the primary key of 33 is null or not.
I was thinking something like:
dim db as DAO.Database
dim rs as DAO.Recordset
set db = CurrentDb
set rs = db.OpenRecordset("record_holdData")
If not isNull(rs.Fields("closedDate")) then
'do nothing
Else
'add a close date
End If
But I don't think this is right. It doesn't specify the record number. In the application, the form is opened by being bound to the record in question, but I don't think CurrentDb takes that into consideration and rather references the entire table.
So my question is, how do open the recordset in this fashion and reference this field in that particular record only?
You found the answer you wanted, but I would use the DLookup Function instead.
Dim db As DAO.Database
Dim strWhere As String
Dim varClosedDate As Variant
Set db = CurrentDb
strWhere = "id = 33"
varClosedDate = DLookup("closedDate","record_holdData",strWhere)
If IsNull(varClosedDate) = True Then
'use today's date as closedDate
db.Execute "UPDATE record_holdData Set closedDate = Date() WHERE " & strWhere
End If
I was under the impression that the argument for the .OpenRecordset() method was to be a table name only. But it turns out you can send it a query too:
set rs = db.OpenRecordset("select * from record_holdData where id = 33")