首页 > 解决方案 > 尽管值发生了许多变化,但我在 vba 中的代码仅产生 0 作为结果

问题描述

我在 excel vba 中编写了一个代码,但它只产生结果为 0。

Function NDAB(value, average) As Integer
    Dim Val As Integer
    Val = average - value
    If Val > 0 Then
        NDAB = Val / average
    Else
        NDAB = 0
    End If
End Function

标签: excelvba

解决方案


在不确切知道您的数字和平均值可以容纳的情况下,您没有将它们定义为整数或双精度数或长整数

此外,如果您的价值大于平均值,您的价值将是负数。

如果您将代码重写为子代码并使用 F8 运行它,您可以逐步看到会发生什么。

Sub test()
Dim value As Integer
Dim average As Integer
Dim NDAB As Integer

value = 2
average = 5

    Dim Val As Integer
    Val = average - value
    If Val > 0 Then
        NDAB = Val / average
    Else
        NDAB = 0
    End If

    MsgBox NDAB 
End Sub

结果为 1 所以对我来说代码很好,输入只是导致 0。


推荐阅读