Need to hide a column in a table on button click - ms-access

I have a button that calls a macro which opens up a table. I'd like to hide a column in that table when it opens. The macro opens the table tChart1_Reportable and I'd like to hide the ID column.
I figure this has to be done in VBA with the RunCode action selected in the macro.
I haven't had luck finding code that works. Found this online but it doesnt work in the current form:
Public Sub SetColumnHidden()
Dim dbs As DAO.Database
Dim fld As DAO.Field
Dim prp As DAO.Property
Const conErrPropertyNotFound = 3270
' Turn off error trapping.
On Error Resume Next
Set dbs = CurrentDb
' Set field property.
Set fld = dbs.TableDefs!tChart1_Reportable.Fields!ID
fld.Properties("ColumnHidden") = True
' Error may have occurred when value was set.
If Err.Number <> 0 Then
If Err.Number <> conErrPropertyNotFound Then
On Error GoTo 0
MsgBox "Couldn't set property 'ColumnHidden' " &; _
"on field '" &; fld.Name &; "'", vbCritical
Else
On Error GoTo 0
Set prp = fld.CreateProperty("ColumnHidden", dbLong, True)
fld.Properties.Append prp
End If
End If
Set prp = Nothing
Set fld = Nothing
Set dbs = Nothing
End Sub

Although you really should think about using a query to accomplish this goal instead, the problem with this code is definitely that the Table itself does not refresh the hidden property on execution.
That being said, this would likely suffice as a solution to this problem:
Public Sub SetColumnHidden()
Dim dbs As DAO.Database
Dim fld As DAO.Field
Dim prp As DAO.Property
Set dbs = CurrentDb
'Set field property.
Set fld = dbs.TableDefs!tChart1_Reportable.Fields!ID
fld.Properties("ColumnHidden") = True
DoCmd.Close acTable, "tChart1_Reportable"
DoCmd.OpenTable "tChart1_Reportable"
Set prp = Nothing
Set fld = Nothing
Set dbs = Nothing
End Sub
To work this through a query, create a new query with Query Design, open it in SQL view. Your query should like something like this:
SELECT [Field1],
[Field2],
[Field3]
FROM tChart1_Reportable
Basically, add every field you want to view (by the field's name), removing the "ID" field from the list. This will accomplish what you're attempting to do. As far as why the code is not working for you, all I can say is it should be.

Related

How can I create button to search database column names in MS Access?

I am trying to create a button in MS Access 2013 that allows a user to search a database for a column containing input text. I was able to find the search code in this post ( Find a table when you know the name of a column? ) but I can't figure out how to bind it to a button. Also when I run the search function from main it doesn't give any output. The only way I can get the search function to work is to hard code the search string into the function.
Sub Main()
Dim inStr As String
ListTablesWithColumnNamesContaining (InputBox("Name contains", "Search"))
End Sub
Public Sub ListTablesWithColumnNamesContaining(ByVal pText As String)
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field
Set db = CurrentDb
For Each tdf In db.TableDefs
For Each fld In tdf.Fields
If InStr(1, fld.Name, "pText", vbTextCompare) > 0 Then
Debug.Print tdf.Name & ":", fld.Name
End If
Next fld
Next tdf
Set fld = Nothing
Set tdf = Nothing
Set db = Nothing
End Sub
You should create a form, put a button inside it choosing button from the Design menu tab.
Then you need to double click the button, and you will open the properties window. Inside this window in the event tab, you need to double click the "on click" row and then press the ".." button on the side.
Now you should see the VBA Editor with the cursor inside this function:
Private function button1_onClick (....)
End Function
You can copy and paste your code here inside and obtain this:
Private function button1_onClick (....)
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field
Dim pText As String
pText = InputBox("Name contains", "Search")
Set db = CurrentDb
For Each tdf In db.TableDefs
For Each fld In tdf.Fields
If InStr(1, fld.Name, pText, vbTextCompare) > 0 Then
Msgbox tdf.Name & ":" & fld.Name
End If
Next fld
Next tdf
Set fld = Nothing
Set tdf = Nothing
Set db = Nothing
End Function
Note that, as HansUp commented, you need to remove the quotes surrounding pText. I've also put the InputBox command directly inside this function and substituted the debug.print with a Message Box.

Access only filtered values in a MS Access table

Is it possible to get the values from rows in an Access table that are showing after the filter is applied?
Example as requested:
I have a table in which employees fill in project tasks, hours on the project etc.
It is made as a table on a form. The columns has limited choices in Initials, Project number, etc. People like to sort the table by the built in filter function in access tables and queries. I filtered so only the project LT1075 is shown in the example.
How can i get those 4 rows as a recordset or something similar? I need to get the values in all hour fields. I need also to copy only those 4 lines in VBA and do stuff to it (Functions wanted by people). But when i use the DAO, i get all rows in the "Unfiltered" table.
How do i get only the rows visible?
In excel, there is a simple function, something with cells_visible but i cant find a pardon to Access.
Best Regards, Emil.
Edit, tryouts:
Public Sub Test1_Click()
Dim rs As DAO.Recordset
Set rs = Me.RecordsetClone
While Not rs.EOF
' Do calculation stuff on record.
rs.MoveNext
Wend
End Sub
It is put on the "Test 1" button in the figure above.
I get the error: "Runtime error 7951 - You entered an expression that has an invalid reference to the RecordsetClone property"
I have a clue that it does not work because of the Me.* function? Since the table is in some sort of subform. But i see only one form in the Navigation panel. (Hidden are also showed).
You can use the RecordsetClone of the form:
Dim rs As DAO.Recordset
Set rs = Me.RecordsetClone
While Not rs.EOF
' Do calculation stuff on record.
rs.MoveNext
Wend
And you can add records to a recordset:
Public Sub CopyRecords()
Dim rstSource As DAO.Recordset
Dim rstInsert As DAO.Recordset
Dim fld As DAO.Field
Dim strSQL As String
Dim lngLoop As Long
Dim lngCount As Long
strSQL = "SELECT TOP 1 * FROM tblStatus"
Set rstInsert = CurrentDb.OpenRecordset(strSQL)
' rstSource can be any recordset, here the RecordsetClone of the form.
Set rstSource = Me.RecordsetClone
With rstSource
While Not .EOF
With rstInsert
.AddNew
For Each fld In rstSource.Fields
With fld
If .Attributes And dbAutoIncrField Then
' Skip Autonumber or GUID field.
ElseIf .Name = "Total" Then
' Special cases.
' Insert default job code.
rstInsert.Fields(.Name).Value = 0
ElseIf .Name = "PROCESSED_IND" Then
rstInsert.Fields(.Name).Value = vbNullString
Else
' Copy field content.
rstInsert.Fields(.Name).Value = .Value
End If
End With
Next
.Update
End With
.MoveNext
Next
rstInsert.Close
.Close
End With
Set rstInsert = Nothing
Set rstSource = Nothing
End Sub

How to set rich text property when creating memo field in DAO?

I'm creating a table with a memo field in DAO.
However, I don't know how to set/create the rich text property for the field.
The following code gives a run time error:
Sub CreateTable()
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field2
Set db = CurrentDb
' Create table
Set tdf = db.CreateTableDef
tdf.Name = "myTable"
Set fld = tdf.CreateField("memo_field", dbMemo)
fld.Properties("TextFormat").Value = acTextFormatHTMLRichText '<- getting error here
tdf.Fields.Append fld
db.TableDefs.Append tdf
db.TableDefs.Refresh
Application.RefreshDatabaseWindow
Set fld = Nothing
Set tdf = Nothing
Set db = Nothing
End Sub
Somebody in a forum suggested something like this,
fld.Properties.Append fld.CreateProperty("TextFormat", dbByte, acTextFormatHTMLRichText)
but I was not able to implement this.
I guess I just go the syntax wrong. What would be the correct way to implement this?
Thanks for your help!
You may have trouble appending a property to a field that is not yet appended to a TableDef.
Try:
Set fld = tdf.CreateField("memo_field", dbMemo)
tdf.Fields.Append fld
tdf.Fields(fld.Name).Properties.Append fld.CreateProperty("TextFormat", dbByte, acTextFormatHTMLRichText)

Access query need to bypass "enter parameter value" error with a msg box saying field not found

I have a simple query tied to a command button that shows a summary of the values in a particular field. It's running on a table that changes with each use of the database, so sometimes the table will contain this field and sometimes it won't. When the field (called Language) is not in the file, the user clicks the command button and gets the "Enter Parameter Value" message box. If they hit cancel they then get my message box explaining the field is not present in the file. I would like to bypass the "Enter Parameter Value" and go straight to the message if the field is not found. Here is my code:
Private Sub LangCount_Click()
DoCmd.SetWarnings False
On Error GoTo Err_LangCount_Click
Dim stDocName As String
stDocName = "LanguageCount"
DoCmd.OpenQuery stDocName, acNormal, acEdit
Err_LangCount_Click:
MsgBox "No Language field found in Scrubbed file"
Exit_LangCount_Click:
Exit Sub
DoCmd.SetWarnings True
End Sub
You can attempt to open a recordset based on the query before you run the query:
Set rs = CurrentDb.QueryDefs("query1").OpenRecordset
This will go straight to the error coding if anything is wrong with the query.
Alternatively, if it is always the language field and always in the same table, you can:
sSQL = "select language from table1 where 1=2"
CurrentDb.OpenRecordset sSQL
This will also fail and go to your error coding, but if it does not fail, you will have a much smaller recordset, one with zero records.
You can easily enough get a list of fields in a table with ADO Schemas:
Dim cn As Object ''ADODB.Connection
Dim i As Integer, msg As String
Set cn = CurrentProject.Connection
Set rs = cn.OpenSchema(adSchemaColumns, Array(Null, Null, "Scrubbed"))
While Not rs.EOF
i = i + 1
msg = msg & rs!COLUMN_NAME & vbCrLf
rs.MoveNext
Wend
msg = "Fields: " & i & vbCrLf & msg
MsgBox msg
More info: http://support.microsoft.com/kb/186246
You have a command button named LangCount. It's click event has to deal with the possibility that a field named Language is not present in your Scrubbed table.
So then consider why a user should be able to click that command button when the Language field is not present. When the field is not present, you know the OpenQuery won't work (right?) ... so just disable the command button.
See if the following approach points you to something useful.
Private Sub Form_Load()
Me.LangCount.Enabled = FieldExists("Language", "Scrubbed")
End Sub
That could work if the structure of Scrubbed doesn't change after your form is opened. If the form also includes an option to revise Scrubbed structure, update LangCount.Enabled from that operation.
Here is a quick & dirty (minimally tested, no error handling) FieldExists() function to get you started.
Public Function FieldExists(ByVal pField As String, _
ByVal pTable As String) As Boolean
Dim blnReturn As Boolean
Dim db As DAO.Database
Dim fld As DAO.Field
Dim tdf As DAO.TableDef
Set db = CurrentDb
' next line will throw error #3265 (Item not found in this collection) '
' if table named by pTable does not exist in current database '
Set tdf = db.TableDefs(pTable)
'next line is not actually needed '
blnReturn = False
For Each fld In tdf.Fields
If fld.Name = pField Then
blnReturn = True
Exit For
End If
Next fld
Set fld = Nothing
Set tdf = Nothing
Set db = Nothing
FieldExists = blnReturn
End Function

MS ACCESS 2007 VBA : DAO recordset....how can I view all the "fields" in the returned collection

so if i do a SQL statement like so:
sql = "SELECT * FROM tblMain"
set rs = currentdb.openrecordset(sql)
what method can i use to view every "field name" in this collection i have just created. i am getting some very strange error stating that the item is not found in this collection.
i know the field exists in the table, i have triple checked the spelling everywhere when i reference it, and the SQL should be pulling everything, but i want to see it.
is there a debug.print method to see all these fields
thanks
Justin
This is a variation on the other answers, but I believe it's better to use a For/Each loop than a counter:
Dim rs As DAO.Recordset
Dim fld As DAO.Field
Set rs = CurrentDB.OpenRecordset("SELECT * FROM tblMain")
For Each fld In rs.Fields
Debug.Print fld.Name
Next fld
Set fld = Nothing
rs.Close
Set rs = Nothing
You can iterate through the fields collection of the recordset.
Code is OTTOMH
Dim NumFields as Integer
For NumFields = 0 to rs.Fields.Count -1
Debug.Print Rs.Fields(NumFields).Name
Next
Alternately, you can set a breakpoint at set rs = currentdb.openrecordset(sql) and then as soon as the statement executes, right-click on rs, choose add watch and view the whole thing in the Watches window.
Here is a script that will look for a field containing the string you specify in every table in an Access database (except System and Attached Tables) and write it to text files:
Option Compare Database
Option Explicit
Sub main()
Dim db As Database
Dim rs As Recordset
Dim bFinished As Boolean
Dim sFieldName As String
Dim iPosition, z, x As Integer
Dim bRetVal As Boolean
Dim tdTemp As TableDef
Dim iDatabaseNumbers As Integer
Const FIELD_TO_FIND = "FieldName"
Set db = CurrentDb
Open Left(db.Name, Len(db.Name) - 4) & "_" & FIELD_TO_FIND & ".txt" For Output As #1
For x = 0 To db.TableDefs.Count - 1
Set tdTemp = db.TableDefs(x)
bRetVal = IIf(tdTemp.Attributes And dbSystemObject, False, True)
If bRetVal Then
bRetVal = IIf(tdTemp.Attributes And dbAttachedTable, False, True)
End If
If bRetVal Then
Set rs = db.OpenRecordset(db.TableDefs(x).Name)
If rs.RecordCount > 0 Then
For z = 0 To rs.Fields.Count - 1
sFieldName = rs.Fields(z).Name
If InStr(1, sFieldName, FIELD_TO_FIND, vbTextCompare) > 0 Then
Print #1, db.TableDefs(x).Name
Exit For
End If
Next z
End If
End If
Next x
Close #1
MsgBox "Done"
End Sub
You could adjust accordingly to make it do what you need.