首页 > 解决方案 > 根据选项按钮选择将文本框正值转换为负值

问题描述

我正在使用带有文本框的 Excel 用户表单,供用户输入收到或给出的美元金额。选择命令按钮后,该数字将放入电子表格单元格中。我有两个单选按钮,一个是给钱的,另一个是收钱的。

I would like the user to enter a positive amount in the box and when the given button is selected it turns into a negative. 当接收到的按钮被选中时,它将使该框保持为正。

通常我会乘以 -1 将其变为负数。我试过了userform.textbox.value = userform.textbox.value * -1

Private Sub InsTxtBox_AfterUpdate()

    GameLogUF.InsTxtBox = Format(GameLogUF.InsTxtBox, "$#,###")

    If GameLogUF.InsPlyrOptnBtn.Value = True Then
        GameLogUF.InsTxtBox.Value = GameLogUF.InsTxtBox.Value * -1
    End If

End Sub

标签: excelvbatextboxuserform

解决方案


首先,检查是否触发了事件。在这个 sub 中放置一个断点并尝试更改该值。

AfterUpdate事件在控件或记录更新时触发。在一条记录中,当控件失去焦点或用户按下 Enter 或 Tab时,每个控件中更改的数据都会更新。

刚刚检查了您的代码,如果事件被触发,它就可以工作。

另外,我建议稍微改变一下。

Dim value As Double
Dim tryValue As String
'remove $ sign so String value could be converted to Number format
tryValue = Replace(GameLogUF.InsTxtBox.value, "$", "")

'if user input is not numeric after removing $ sign - input incorrect
If Not IsNumeric(tryValue) Then
    'do sth else
    Exit Sub
End If
value = tryValue

' "= True" part is not needed there is no need to compare boolean property '
If GameLogUF.InsPlyrOptnBtn.value Then
    'if user input is negative your code will turn it back to positive, with Abs it always will be negative in this case'
    value = Abs(value) * -1
End If
'do formatting in the end'
GameLogUF.InsTxtBox.value = Format(value, "$#,###")

推荐阅读