Search code examples
vbafunctionms-accesstextboxsubroutine

MS-ACCESS How to change a textbox font color via subroutine or function


I have some textboxes in a form and i set one them with these properties by default

txtSearchBox.Value = "Wait.."
txtSearchBox.ForeColor = 2
txtSearchBox.FontItalic = True

I want to add an onClick event to this txtSearchBox in order to change its properties via a subroutine or function because i want to use this sub/fun on other textboxes..

so i declared a global variable

Dim CurrentCtrl As Object

and tryed to do the job..

Private Sub txtSearchBox_Click()
CurrentCtrl = txtSearchBox.Name
txtWait4Input (CurrentCtrl)
End Sub

Private Sub txtWait4Input(CurrentCtrl As Object)
CurrentCtrl.ForeColor = 0
CurrentCtrl.FontItalic = False
CurrentCtrl.Value = Null
End Sub

but this doesn't work..


Solution

    1. use Set

    2. remove parens from sub call

    3. use Controls collection

    4. Dim statement does not create a global variable, that requires Global or Public, Dim declares a variable that is available only to the module it is declared in

    5. variable CurrentCtrl should not be declared in two locations

    So if all code is behind form:

    Dim CurrentCtrl As Object
    _________________________________________
    Private Sub txtSearchBox_Click()
    Set CurrentCtrl = Me.Controls("txtSearchBox")
    txtWait4Input
    End Sub
    _________________________________________
    Private Sub txtWait4Input()
    CurrentCtrl.ForeColor = 0
    CurrentCtrl.FontItalic = False
    CurrentCtrl.Value = Null
    End Sub
    

    Could eliminate variable in header and Set line:

    Private Sub txtSearchBox_Click()
    txtWait4Input Me.Controls("txtSearchBox")
    End Sub
    _________________________________________
    Private Sub txtWait4Input(CurrentCtrl As Object)
    CurrentCtrl.ForeColor = 0
    CurrentCtrl.FontItalic = False
    CurrentCtrl.Value = Null
    End Sub