Private Sub 权重_KeyDown(KeyCode As Integer, Shift As Integer) If KeyCode <> vbKeyReturn And KeyCode <> vbKeyUp And KeyCode <> vbKeyDown And vbKeyTab Then Exit Sub 权重.Text = M1.CalculateExpression(权重.Text) End Sub '公共函数 Function CalculateExpression(Expression As Variant) As Variant '当Expression为"=","+","-"号开头时,计算它的表达式,并返回结果 CalculateExpression = Expression Dim sE As String sE = Left(Expression, 1) If Not ("=+-" Like "*" & sE & "*") Then Exit Function Dim result As Variant On Error GoTo err Select Case sE Case "=", "+" result = Eval(MID(Expression, 2)) Case "-" result = Eval(MID(Expression, 1)) End Select CalculateExpression = result Exit Function err: 'Empty End Function
为什么是键按下事件,而不是变更后事件呢?
因为如果你的字段设置为数字类型的话,你连数据验证都过不了,也就没办法触发代码了.
延伸:
1.可以限制用户值上限.比如当前库存上限或者下限.比如库存只有100个,当用户输入的值,或者表达式返回的结果超过100时,可以强制用户最多只能输入100
2.计算表达式的同时,可以把表达式写入"备注"字段中.很多公司的送货单都有要求备注件数与规格,比如送货数量是100个,每件10个,共10件,那备注就是10*10.
标签:CalculateExpression,10,ACCESS,数据表,result,简单,100,Expression,KeyCode From: https://www.cnblogs.com/yoooos/p/18246895