【发布时间】:2017-02-23 20:43:31
【问题描述】:
我正在尝试将在表单上创建的 TextBox 传递给子例程,以检查 TextBox 的内容并将 TextBox 限制为仅限数字数据。由于 VBA 没有重载,我使用可选参数来调用函数,而不使用任何参数作为 TextBox_Exit 事件的一部分,或者作为独立调用,将有问题的文本框作为参数传递(我不得不解决这个事实如果焦点转移到当前帧之外的控件,则不会引发 TextBox_Exit 事件)。
我遇到的问题是当我使用这段代码时:
Private Sub fLaser_Exit(ByVal Cancel As msForms.ReturnBoolean)
OnlyNumbers (tbLaserCutLength)
OnlyNumbers (tbPartWidth)
OnlyNumbers (tbPartLength)
OnlyNumbers (tbLaserBendQty)
oPart.LaserCutLength = CDec(tbLaserCutLength.Value)
oPart.SheetMetalWidth = CDec(tbPartWidth.Value)
oPart.SheetMetalLength = CDec(tbPartLength.Value)
oPart.LaserCutLength = CInt(tbLaserBendQty.Value)
UpdateCosts
End Sub
Private Sub OnlyNumbers(Optional ByRef tb As msForms.TextBox = Nothing)
On Error GoTo ErrorHandler:
If (tb Is Nothing) Then
Set ac = ActiveControl
Do While (TypeOf ac Is msForms.Frame)
Set ac = ac.ActiveControl
Loop
If TypeOf ac Is msForms.TextBox Then
With ac
If Not IsNumeric(.Value) Then
.Value = 0
End If
End With
End If
Else:
With tb
If Not IsNumeric(.Value) Then
.Value = 0
End If
End With
End If
ErrorHandler:
End Sub
问题在于 OnlyNumbers(tbLaserCutLength) 调用(以及后续的 OnlyNumber 调用。我收到运行时错误“424”:需要对象错误。tbLaserCutLength 是使用 Excel VBA 表单编辑器创建的文本框。如果我不要将任何参数传递给 OnlyNumbers 子例程完全按预期工作。
如果我在 tbLaserCutLength 上放置一个手表,对象浏览器会说一个对象/文本框,而不仅仅是一个文本框。我怀疑问题出在子例程声明中使用的 msForms.TextBlock 类型。我已经尝试过 TextBlock 并且得到了相同的结果。我应该使用另一个父类吗?或者,我是否在做其他完全错误的事情?
【问题讨论】: