MS Access VBA to enable / disable a text box - vba

I have the below VBA code in access to enable/disable a text box.
When the code is executed the tonnes textbox remains disabled.
Am I missing an additional property?
Private Sub EnableTonnes()
Dim sCode As String
sCode ="xx"
' set default values for tonnes enabled and locked properties
Tonnes.enabled = False
Tonnes.Locked = True
If sCode = "xx" Then
' enable tonnes field
Tonnes.enabled = True
Tonnes.Locked = False
End If
End Sub

Your code looks ok. TextBox properties are set in form design mode and can only be permanently changed in form design mode. You do some sophisticated coding to open the form in design mode, change the properties and then save the form... or do it manually. You will always be able to use your code to control those properties at runtime.
Option Compare Database
Option Explicit
Private Sub cmdGo_Click()
Dim sCode As String
sCode = "xx"
' set default values for tonnes enabled and locked properties
txtTonnes.Enabled = False
txtTonnes.Locked = True
If sCode = "xx" Then
' enable tonnes field
txtTonnes.Enabled = True
txtTonnes.Locked = False
End If
MsgBox txtTonnes.Name & " Enabled status is " & txtTonnes.Enabled
MsgBox txtTonnes.Name & " Locked status is " & txtTonnes.Locked
End Sub
Private Sub Form_Load()
MsgBox txtTonnes.Name & " Enabled status is " & txtTonnes.Enabled
MsgBox txtTonnes.Name & " Locked status is " & txtTonnes.Locked
End Sub

Related

Access modal form updates database then calling form update does not

In Access a header form needs an address associated with it. The header form calls a modal address form. On Save the modal address form will write the address ID to the header form's record source address ID then close. Coming back to the calling header form should then list the related address ID after a requery, that is the FK link. I am not getting the address form's address ID written to the header form's record source address ID field and thus not listing on requery. A fair amount of this code is based on several SO questions.
The header form calls a wrapper function to manage the modal address form:
Private Sub txtJob_AfterUpdate()
gbolDropShipAddressCompleted = False
'Use global variables for use in frmDropShipAddress SQL update statement
gtxtCurrentJobNumber = Me.Job
gtxtCurrentJobRelease = Me.REL
gtxtCurrentJob = Me.txtJob
'Call the wrapper function
gbolDropShipAddressCompleted = fNewDropShipAddressCompletion()
If gbolDropShipAddressCompleted = True Then
'Me.Dirty = False
Me.Requery
With Me.RecordsetClone
.FindFirst "[Job] = '" & gtxtCurrentJobNumber & "' And [REL] = '" & gtxtCurrentJobRelease & "'"
If Not .NoMatch Then
If Me.Dirty Then
Me.Dirty = False
End If
Me.Bookmark = .Bookmark
End If
End With
'Reset all variables
gbolDropShipAddressCompleted = False
gtxtCurrentJobNumber = ""
gtxtCurrentJobRelease = ""
gtxtCurrentJob = ""
End If
End Sub
The wrapper function:
Public Function fNewDropShipAddressCompletion() As Boolean
'Manages call to frmDropShipAddress
DoCmd.OpenForm "frmDropShipAddress", , , , , acDialog, "From frmPackingSlipHeader"
fNewDropShipAddressCompletion = gbolfrmDropShipAddressTofrmPackingSlipHeader
DoCmd.Close acForm, "frmDropShipAddress"
End Function
The modal form's two events:
Private Sub btnSaveAddressInfo_Click()
DoCmd.RefreshRecord
'Update MAIN table with new address id using global variables
CurrentDb.Execute " UPDATE [MAIN] " & _
" SET intADDRESS_ID = " & Me.txtAddress_ID & _
" WHERE JOB = '" & gtxtCurrentJobNumber & "'" & _
" AND REL = '" & gtxtCurrentJobRelease & "'"
gbolfrmDropShipAddressTofrmPackingSlipHeader = True
Me.Visible = False
End Sub
Private Sub Form_Open(Cancel As Integer)
gbolfrmDropShipAddressTofrmPackingSlipHeader = 0
If Me.OpenArgs = "From frmPackingSlipHeader" Then
DoCmd.GoToRecord , , acNewRec
'Coded because TabCtlDatePicker opens all forms and openargs is NULL and causes all forms to be affected
ElseIf IsNull(Me.OpenArgs) Then
Exit Sub
' Else
' Me.PopUp = True
' Me.Modal = True
' Me.BorderStyle = 1
' Me.NavigationButtons = False
' Me.RecordSelectors = False
End If
End Sub
The Access front-end uses several tab controls to select between many different reports/date and or data pickers all sorted into tab control pages by topic. The back-end is MS SQL server via linked tables. The address form may be opened for generic viewing or called (modal). I can't seem to get the correct VBA to get the address form's address ID written to the header's record source and the VBA to get the header to requery and return to the correct record. Any help would be appreciated and TIA.
Tim

Highlight field background in continuous form

I have an Access continuous form. I would like to change the forecolor of a specific record's field.
I have the field to highlight from the FieldModified field. So for example FieldModified = "Converted". Converted being a field on my form.
I would like to change the color of the "Converted" field, and do this for each record in the form.
I thought this code would work, but I get an error on Me.[FieldModified].ForeColor. And I need to do this for each record in the form.
Code:
Private Sub Form_Load()
Dim fldName As String
fldName = Me.FieldModified.value
If (Not IsNull(fldName)) Then
Me.[fldName].ForeColor = vbRed '<--doesn't recognize fldName value
End If
End Sub
Updated code but it gives me an error 438 saying object doesn't support this property or method. But the form does highlight fields on the form but it highlights more then the one field "fldName"
Private Sub Form_Load()
Dim rstForm As String
Dim fldName As String
Set rstForm = Me.ChangedData.Form.Recordset
Do While Not rstForm.EOF
fldName = Me.FieldModified.value
If (Not IsNull(fldName)) Then
Me.Controls(fldName).ForeColor = vbRed '<--doesn't recognize fldName value
End If
rstForm.MoveNext
Loop
End Sub
You set the default format for the control. Every copy of the control in the continuous form uses this format. To format by a condition (fldName = Me.FieldModified.value) you need Condtional Formatting as Andre told you or use the detail-sections paint event (see update on bottom)
In conditional format wizard, you can create a condtion withExpression Isand[Converted].Name = [FieldModified]for each control of the form that should be highlighted, if its name matchesFiledModified. In Ms Access expressions you can't useMe, just omit it .
You can use VBA to format all controls with FormatConditions by code. If you want to modify an existing condition use.Modifyinstead of.Add
Private Sub Form_Load()
Dim ctl As Access.Control
For Each ctl In Me.Controls ' loop through all controls of form
On Error Resume Next ' Not all controls can have conditional format (e.g. labels). To save the check of control type, we ignore errors here
ctl.FormatConditions.Add(acExpression, , ctl.Name & ".Name=[FieldModified]").BackColor = vbRed 'add o format condition to control if possible, else an error is raised but ignored
If Err.Number Then 'show errors
Debug.Print "Error: " & Err.Number & " - " & Err.description & " in Control: " & ctl.Name & " Type is " & TypeName(ctl)
Err.Clear 'reset error to catch next
Else
Debug.Print "FormatCondition added to Control: " & ctl.Name & " Type is " & TypeName(ctl)
End If
Next ctl
On Error GoTo 0 ' turn on errors again, maybe add an error handler (On Error Goto MyErrHandler)
End Sub
Update:
You can use theDetails_Paintevent of the form to format same control different per record. This enables conditional format for controls withoutFormatConditionsproperty like labels, buttons.
Private Sub Detail_Paint()
Dim c As Access.Control
For Each c In Me.Detail.Controls
If c.Name = Me.FieldModified.Value Then
c.ForeColor = vbRed
Else
c.ForeColor = vbBlack
End If
Next
End Sub
You can't use a String variable like this, fldName is an identifier holding a String value.. not an identifier - in Me.ControlName, both Me and ControlName are identifiers.
But not all hope is lost! You can use a String to pull a Control object from a form!
All form controls should exist in the form's Controls collection, keyed by name:
Me.Controls(fldName).ForeColor = vbRed

Access. How to Create a record and select that record in CBO on another form?

I have two forms frmProductCreate and frmColourCreate.
In frmProductCreate I have:
Combobox: colourID
Button: btnColCreate
The idea is that if a user needs to create a new colour, they can click on the create button which opens frmColourCreate, name the new colour and click save button. Which will save the new colour in the colours table (which is the record source for the cbo ColourID in frmProductCreate). Then requery colourID in frmProductCreate and close frmColourCreate.
What I also want this save button to do is after the requery to select the cbo colourID and go to the last created colour. i.e. the last record. I have tried a few codes but failed to make it work. Any help will be greatly appreciated.
Private Sub btnSavecol_Click()
Dim cancel As Integer
If Me.ColName = "" Then
MsgBox "You must enter a Colour Name."
DoCmd.GoToControl "ColName"
cancel = True
Else
If MsgBox("Are you sure you want to create new Colour?", vbYesNo) = vbNo Then
cancel = True
Else
CurrentDb.Execute " INSERT INTO Colours (ColName) VALUES ('" & Me.ColName & "')"
Me.ColName = ""
DoCmd.Close
If CurrentProject.AllForms("frmProductCreate").IsLoaded = False Then
cancel = True
Else
Forms!frmproductCreate!ColourID.Requery
'Forms!frmproductCreate!ColourID.SetFocus
'Forms!frmproductCreate!ColourID.items.Count = -1
'Forms!frmproductCreate!ColourID.Selected(Forms!frmproductCreate!ColourID.Count - 1) = False
'YourListBox.SetFocus
'YourListBox.ListIndex = YourListBox.ListCount - 1
'YourListBox.Selected(YourListBox.ListCount - 1) = False
End If
If CurrentProject.AllForms("frmProductDetails").IsLoaded = False Then
cancel = True
Else
Forms!frmproductDetails!ColourID.Requery
End If
End If
End If
End Sub
Some remarks:
Whatfor is the variable cancel? Because it is not used, I removed it.
I have no really idea whatfor you need Me.ColName = "".
Why do you close the current form so early? I moved DoCmd.Close to the end.
I made your code a bit more readable, by removing 'arrow-code' (those nested IFs).
Finally try this:
Private Sub btnSavecol_Click()
If Me.ColName.Value = "" Then
MsgBox "You must enter a Colour Name."
DoCmd.GoToControl "ColName"
Exit Sub
End If
If MsgBox("Are you sure you want to create new Colour?", vbYesNo) = vbNo Then Exit Sub
CurrentDb.Execute "INSERT INTO Colours (ColName) VALUES ('" & Me.ColName.Value & "')"
If Not CurrentProject.AllForms("frmProductCreate").IsLoaded Then GoTo Done
Forms!frmproductCreate!ColourID.Requery
'This sets the ComboBox 'ColourID' to the new colour:
'Forms!frmproductCreate!ColourID.Value = Me.ColName.Value
'If you use an automatic generated ID in the table 'Colours', then you will have to get that ID from the color and set it to the ComboBox:
Forms!frmproductCreate!ColourID.Value = DLookup("ColID", "Colours", "ColName = '" & Me.ColName.Value & "'")
Me.ColName.Value = ""
If Not CurrentProject.AllForms("frmProductDetails").IsLoaded Then GoTo Done
Forms!frmproductDetails!ColourID.Requery
Done:
DoCmd.Close
End Sub

VBA ThisWorkbook.SaveAs Filename:=SaveAsName custom name (SaveAsName) not appearing in dialog

I'm hoping somebody can help me with this. I'm creating a model in Excel using VBA and want to populate the Save As dialog with a custom filename. I have three pieces of code. The first is for a userform that asks the end-user to enter the name of their facility:
Private Sub cmdNext_Click()
strHospName = frmHospName.txtHospName.Value
' Check for a usable hospital name
If Len(strHospName) = 0 Then
frmHospName.Hide
MsgBox "Please provide the name of your facility.", vbCritical + vbOKOnly, "Missing Facility Name"
frmHospName.Show
End If
If (Len(strHospName) - Len(Trim(strHospName)) = Len(strHospName)) Then
frmHospName.Hide
MsgBox "Please provide the name of your facility.", vbCritical + vbOKOnly, "Missing Facility Name"
frmHospName.Show
End If
If strHospName Like "*[\/:*?""<>|]*" Then
frmHospName.Hide
MsgBox "Please enter your facility's name without any of the following characters: \ / : * ? < > | ", vbCritical + vbOKOnly, "Invalid Facility Name"
frmHospName.Show
End If
Call SaveAsNameStore(strHospName, MyName)
Set currForm = Me
Unload Me
End Sub
The second piece lives in its own module and checks to see if this model has already been customized (a customized model will not see frmHospName upon workbook open, thus strHospName will not get assigned), and based on that check, it creates the string SaveAsName:
Public strHospName As String
Public SaveAsName As String
Function MyName() As String
MyName = ThisWorkbook.Name
End Function
Sub SaveAsNameStore(strHospName As String, MyName As String)
' This code creates a custom SaveAs name
Dim strModelDate As String
strModelDate = Format(Now, "mm-dd-yyyy")
If (Len(strHospName) - Len(Trim(strHospName)) = Len(strHospName)) Then
SaveAsName = MyName
Else
SaveAsName = strHospName & " customized economic model " & strModelDate
End If
End Sub
The third piece lives in ThisWorkbook and applies SaveAsName in Workbook_BeforeSave:
Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
''This code forces SaveAs with custom filename instead of Save to prevent overwriting the master model file
''NEED TO UNCOMMENT PRIOR TO DELIVERY
Application.ScreenUpdating = False
If SaveAsUI = False Then
Cancel = True
ElseIf SaveAsUI = True Then
With Application.FileDialog(msoFileDialogSaveAs)
Application.EnableEvents = False
If .Show Then
ThisWorkbook.SaveAs Filename = SaveAsName
End If
Application.EnableEvents = True
End With
Cancel = True
End If
End Sub
The problem is that, when I click the "Save As" button, the custom SaveAs name isn't populating in the dialog. I can see that SaveAsName is generated correctly via ?SaveAsName in the Immediate window. For syntax, I've tried both ThisWorkbook.SaveAs Filename = SaveAsName and ThisWorkbook.SaveAs Filename:=SaveAsName with the same result both times.
Sorry for the long-winded post. I would appreciate any help you can provide!
This is something I use to make a backup of something I'm currently working in, without naming it the same thing. Easily modified for your situation and variables
Private Sub cmdBackupButton_Click()
'__BACKUP THE CURRENT WORKBOOK___
Application.DisplayAlerts = False
ActiveWorkbook.SaveCopyAs "C:\WhateverPathYouWant\myFile_backup.xlsb")
Application.DisplayAlerts = True
End Sub
This eliminates any "save as" dialogue, and needs no interaction. Very simple.

How to get checkbox to function on Access 2010 report?

I’m developing a DB application via MS Access 2010.
I have added an unbound, binary checkbox to a report with the purpose that a user can choose one of two record sources (queries), for two variations of the report.
The checkbox Control Source property is blank and the Triple State is set to No.
However, upon opening the report,
the checkbox is permanently greyed out, no matter haw many times it is clicked!
Also, upon each single click on the checkbox, my_checkbox_Click() fires twice with its value toggling between Null and True!
The Null value seems to be interpreted as False which might be OK if the event didn't double-fire on each single click.
How do I get my checkbox to both appear properly -- as a binary checkbox, toggling between yes and no -- and function correctly, firing _Click() only once per click?
If it's a known issue with no solution, which is the best button type as a workaround?
My code:
Private Sub Report_Load()
Debug.Print vbCrLf & "Report_Load"
Me.my_chk.Value = False
set_data_source
End Sub
Private Sub my_chk_Click()
Debug.Print vbCrLf & "my_chk_Click"
set_data_source
End Sub
Private Sub set_data_source()
Debug.Print vbCrLf & "set_data_source"
Debug.Print "Me.my_chk.Value", Me.my_chk.Value
Debug.Print "Me.my_chk.ControlSource ", Me.my_chk.ControlSource
Debug.Print "Me.my_chk.TripleState ", Me.my_chk.TripleState
Me.RecordSource = IIf(Me.my_chk.Value, "my_yes_qry", "my_no_qry")
Me.Requery
Debug.Print "Me.RecordSource", Me.RecordSource
End Sub
Immediate window:
Report_Load
set_data_source
Me.my_chk.Value False
Me.my_chk.ControlSource
Me.my_chk.TripleState False
Me.RecordSource my_no_qry
' click once on checkbox
my_chk_Click
set_data_source
Me.my_chk.Value Null
Me.my_chk.ControlSource
Me.my_chk.TripleState False
Me.RecordSource my_no_qry
my_chk_Click
set_data_source
Me.my_chk.Value -1
Me.my_chk.ControlSource
Me.my_chk.TripleState False
Me.RecordSource my_yes_qry
' click once on checkbox
my_chk_Click
set_data_source
Me.my_chk.Value Null
Me.my_chk.ControlSource
Me.my_chk.TripleState False
Me.RecordSource my_no_qry
my_chk_Click
set_data_source
Me.my_chk.Value -1
Me.my_chk.ControlSource
Me.my_chk.TripleState False
Me.RecordSource my_yes_qry
The only good news is that the Requery after a RecordSource changes does correctly (if all-too-briefly) affect the data.
Another thing, even though my checkbox doesn't have an AfterUpdate listed under Events, if I replace the above my_checkbox_Click() handler with
Private Sub my_chk_AfterUpdate()
Debug.Print vbCrLf & "my_chk_AfterUpdate"
set_data_source
End Sub
I get
Report_Load
set_data_source
Me.my_chk.Value False
Me.my_chk.ControlSource
Me.my_chk.TripleState False
Me.RecordSource my_no_qry
' click once on checkbox
my_chk_AfterUpdate
set_data_source
Me.my_chk.Value -1
Me.my_chk.ControlSource
Me.my_chk.TripleState False
Me.RecordSource my_yes_qry
' click once on checkbox
my_chk_AfterUpdate
set_data_source
Me.my_chk.Value -1
Me.my_chk.ControlSource
Me.my_chk.TripleState False
Me.RecordSource my_yes_qry
which, as you can see, doesn't work either because now, even though AfterUpdate fires once per click, the checkbox value doesn't change!
Over at access-programmers.co.uk/forums
there was a suggestion (regarding a form, not a report) to use fancy coding
Nz(Me.my_chk = True, False)
which I tried but it had no difference in outcome.
Are you sure a checkbox on a report can be checked as it can in a form? I'm not! But an interesting possibility can be found here.
In the case of a form, it's grayed out because it is unbound and the value isn't set. The solution is to make a form variable and set to that. When the form is loaded, set the variable to False and set the checkbox to the variable. In the AfterUpdate() event of the checkbox, use the value of the control to set the variable. Then run set_data_source. You will probably want to run set_data_source also when the form loads.
Option Explicit
Dim booSourceUsual as boolean
Private Sub MyForm_Load()
booSourceUsual = False
Me!my_chk.Value = booSourceUsual
Call set_data_source
End Sub
Private Sub my_chk_AfterUpdate()
booSourceUsual = Me!my_chk.Value
Call set_data_source
End Sub