通过用户窗体的文本框

问题描述 投票:0回答:1

在一个用户表单中避免为 4 个文本框使用 4 个单独的宏的优雅方法是什么?

Private Sub txt1_Change()
If txt1 = "" Then
txt1.BackColor = vbRed
Else
txt1.BackColor = vbWhite
End If
End Sub
Private Sub txt2_Change()
If txt2 = "" Then
txt2.BackColor = vbRed
Else
txt2.BackColor = vbWhite
End If
End Sub

Private Sub txt3_Change()
If txt3 = "" Then
txt3.BackColor = vbRed
Else
txt3.BackColor = vbWhite
End If
End Sub

Private Sub txt4_Change()
If txt4 = "" Then
txt4.BackColor = vbRed
Else
txt4.BackColor = vbWhite
End If
End Sub

在一个用户表单中避免为 4 个文本框使用 4 个单独的宏的优雅方法是什么?

vba userform
1个回答
0
投票

可以这样安排:

Option Explicit
Private Sub txtx_Change(ByVal txtx As Object)
  If txtx = "" Then
    txtx.BackColor = vbRed
  Else
    txtx.BackColor = vbWhite
  End If
End Sub

Private Sub txt1_Change()
  txtx_Change txt1
End Sub

Private Sub txt2_Change()
  txtx_Change txt2
End Sub

Private Sub txt3_Change()
  txtx_Change txt3
End Sub

Private Sub txt4_Change()
  txtx_Change txt4
End Sub

txtx_Change()
将参数作为活动文本框对象传递。

© www.soinside.com 2019 - 2024. All rights reserved.