excel 编写vba大于和小于代码

63lcw9qa  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(275)

我正在尝试为VBA用户窗体生成代码。
我试图说明,如果一个邮政地区“BT”和重量小于或等于30,那么成本将是15.15英镑,然后将有一个额外的成本为每单位超过30 0.65。
如果邮政编码不是“BT”,且权重小于或等于35,则成本为4.73英镑,每增加一个单位,成本为0.25英镑
我有下面的,但它是不正确的计算。

Private Sub Weighttb_Change()

    If PostCodecb = "BT" Then
        UKMtb = 15.51 + (Weighttb - 30) * 0.65
    ElseIf Weighttb <= 35 And PostCodecb <> "BT" Then
        UKMtb = 4.73 + (Weighttb - 35) * 0.25
    Else
        UKMtb = "4.73"
    End If
End Sub

任何帮助都是感激不尽的
丽莎

uqjltbpv

uqjltbpv1#

我认为您只需要将每个邮政编码的计算分开即可。
此外,如果传递了低于基数的值,例如20而不是30,则计算的第二部分+ (Weighttb - 30) * 0.65将引入误差,因为它将计算-10 * 0.65
请看下面的例子和一些测试。不确定 * 单位 * 是什么,所以我假设它们是整数(整数)。

Private Function CalculateCost(ByVal postCode As String, ByVal weight As Integer) As Double

    Select Case postCode
        Case "BT":
            CalculateCost = 15.51 + IIf(weight > 30, (weight - 30) * 0.65, 0)
        
        Case Else:
            CalculateCost = 4.73 + IIf(weight > 35, (weight - 35) * 0.25, 0)
    End Select
End Function

几个测试来验证结果:

Sub T()

    'BT
    Debug.Print "Expected: " & 15.51, "Got: " & CalculateCost("BT", 30)
    Debug.Print "Expected: " & 15.51 + 5 * 0.65, "Got: " & CalculateCost("BT", 35)
    Debug.Print "Expected: " & 15.51, "Got: " & CalculateCost("BT", 20) 'below base
    
    'Other
    Debug.Print "Expected: " & 4.73, "Got: " & CalculateCost("NBT", 35)
    Debug.Print "Expected: " & 4.73 + 5 * 0.25, "Got: " & CalculateCost("NBT", 40)
    Debug.Print "Expected: " & 4.73, "Got: " & CalculateCost("NBT", 25) 'below base

End Sub

结果:

'Expected: 15.51    Got: 15.51
'Expected: 18.76    Got: 18.76
'Expected: 15.51    Got: 15.51
'Expected: 4.73     Got: 4.73
'Expected: 5.98     Got: 5.98
'Expected: 4.73     Got: 4.73

在你的潜艇里呼叫它:

Private Sub Weighttb_Change()

    UKMtb = CalculateCost(PostCodecb, Weighttb)

End Sub

相关问题