多个文本框调用同一个 VBA 过程

Multiple text boxes to call the same VBA procedure

我正在开发一个 Access 数据库并且有几种形式;所有这些都有相同的文本框。
每个表单的文本框来自相同的记录源、相同的名称、相同的属性等。更新文本框后,我有 VBA 运行 一个 Instr 过程,它捕获这些文本中常用的关键短语框并用常用短语替换它们。
我怎样才能从每个表单中获取每个文本框来调用相同的过程,这样,如果我必须随着时间的推移改进代码,我只会在一个地方这样做,而不是去每个表单更新代码。

示例代码。

textbox1_AfterUpdate()

Dim A as TextBox
Set A= Me.Textbox1

If InStr(A," Attachment Number ") Then
  Me.FunctionalArea.SetFocus
  A=Replace(A,"Attachment Number","<<Att."&" "& Left(Me.FunctionalArea).text,1)&""&"XXX>>")
  A=SetFocus
End If

If InStr(A, " Program Name ") Then
  A = Replace(A, " Program Name ", " <<ProgramNameXX>> ")
End If

If InStr(A, " Office Address ") Then
  A = Replace(A, " Office Address ", " <<OfficeAddressXX>> ")
End If

你可以做到。

当您将该文本框放在每个表单上时,您可以输入以下内容来代替构建“事件”代码存根:

=我的函数名()

或者,在您的情况下,您可以将此代码放在标准代码模块(而不是表单代码模块)中。

Public Function MyGlobalAfterUpdate

   ' pick up the form and the control
   ' do this first, do this fast, do this right away
   ' since a timer event, mouse click, focus change etc. can
   ' case the screen.ActiveForm, and screen.ActiveControl to change
   ' once we grab these values, then you ok
   
   Debug.Print "global after"

   Dim MyControl    As TextBox
   Dim MyForm       As Form

   Set MyForm = Screen.ActiveForm
   Set MyControl = Screen.ActiveControl


   Debug.Print "Control name = " & MyControl.Name
   Debug.Print "Text of control = " & MyControl.Value

   Dim strText As String

   strText = MyControl.Value

   Debug.Print strText

   ' note that we have FULL use of the form values
   ' in place of me!Some value, or control?
   ' you can go
   MyForm.Refresh
   MyForm!LastUpdate = now()
   
   ' save the data in the form
   ' If MyForm.Dirty = true then MyForm.Dirty = False

End sub

所以你可以在这段代码中自由地做任何你想做的事。您只需将表单引用中的“我”替换为 MyForm,但是一旦您获取了活动表单,那么您可以用“我”做任何事情,您也可以用 MyForm 做同样的事情。如前所述,理论上您可以使用 Screen.ActiveForm,但您最好尽可能快地尽快获取参考资料,因为这些值和焦点可能会发生变化,而且通常会发生变化 - 所以 get/grab/take 尽可能快地参考控件。一旦您从屏幕上抓取了参考,那么焦点等的微小变化就无关紧要了 - 因为您立即拿起了表格和控件。

关键概念,关键要点?您可以使用 screen.ActiveForm 获取当前表单,也可以 get/grab 使用 Screen.ActiveControl.

触发更新后事件的当前控件

所以,总结一下:

不要在表单中创建代码存根。在更新事件后的控件中,将 PUBLIC 函数的名称放在标准代码模块中。

例如:

=MyGlobalAfterUpdate()

您只需使用文本框的参数调用代码即可。

类似于

Public Sub textbox1_AfterUpdate()

    DoTextBoxActions Me.Textbox1
    
End Sub


Public Sub DoTextBoxActions(ByRef ipTextBox As TextBox)

        If InStr(ipTextBox.Text, " Attachment Number ") Then
          ipTextBox.FunctionalArea.SetFocus
          ipTextbox=Replace(ipTextbox.Text,"Attachment Number","<<Att."&" "& Left(ipTextbox.FunctionalArea).text,1)&""&"XXX>>")
          ipTextBox.Parent.SetFocus = SetFocus
        End If
        
        If InStr(ipTextBox.Text, " Program Name ") Then
          ipTextBox = Replace(ipTextBox.Text, " Program Name ", " <<ProgramNameXX>> ")
        End If
        
        
        If InStr(ipTextBox.Text, " Office Address ") Then
          ipTextBox = Replace(ipTextBox, " Office Address ", " <<OfficeAddressXX>> ")
        End If
           
End Sub