在 Excel VBA 中的 UDF 之间,但使其考虑小数而不仅仅是整数?

问题描述 投票:0回答:2

我有这个 VBA 函数可以将两个数字之间的值返回到单个单元格中。它对于负数也能正常工作。然而,它不能正确返回四舍五入到最接近整数的小数之间的值。

例如,在 3.5 和 6.5 之间,单元格应该打印 4,5,6,而当前它只打印:5

Function InBetween(MyFirst As Integer, MyLast As Integer)
Dim foo As String
Dim i As Long
foo = MyFirst + 1
For i = MyFirst + 2 To MyLast - 1
foo = foo & "," & i
Next i
InBetween = foo
End Function
excel vba function
2个回答
0
投票

你的问题是你的参数被声明为

Integer
。当您使用小数(可能是
Double
)调用该函数时,VBA 运行时会将参数隐式转换为整数。更糟糕的是,VBA 使用“银行家舍入”,如果通过“5.5”,则会舍入为 6,但“6.5”也会舍入为 6。

因此将参数类型更改为

Double
。现在,您可以使用
Int
函数仅获取起始数字的整数部分,这与路由不同:
Int(3)
是 3,
Int(3.3)
是 3,
Int(3.7)
是 3。

Function InBetween(MyFirst As Double, MyLast As Double)
    MyFirst = Int(MyFirst)
    (...)
End Function 

这可行,但是我发现它有点难以阅读,因为 For 循环的起始值和结束值似乎不是很明显。我想出了以下代码:

Function InBetween(MyFirst As Double, MyLast As Double)
    Dim foo As String
    Dim curVal As Long
    curVal = Int(MyFirst) + 1
    Do While curVal < MyLast
        foo = foo & IIf(foo = "", "", ",") & CStr(curVal)
        curVal = curVal + 1
    Loop
    InBetween = foo
End Function

0
投票

使用

foo = MyFirst + 1
For i = MyFirst + 2 To MyLast - 1
会导致跳过正在生成的字符串中的开始/结束值。 您可以使用 if 语句来确定
foo
值(初始与重复,这样您就不会得到无关的“,”),这样:

Function InBetween(MyFirst As Integer, MyLast As Integer) As Double
    Dim foo As String
    Dim i As Long
    For i = MyFirst To MyLast
        If Len(foo) = 0 Then
            foo = i
        Else
            foo = foo & "," & i
        End If
    Next i
    InBetween = foo
End Function

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.