基于自定义设置舍入值

时间:2014-06-02 22:53:04

标签: vba rounding

下午好,

我有以下代码运行良好,但我需要稍微扩展一下。我需要的是,如果小数是> =#。8,则向上舍入。如果值是< =#。7,则向下舍入。

所以,一个例子是1.7将= 1; 1.8会= 2; -1.7将= -1和-1.8等于-2。

我能写些什么来建立我已经创造的东西吗?

If (Worksheets("DATA_STAGING").Range("X27").Value) > 1 Or (Worksheets("DATA_STAGING").Range("X27").Value) < -1 Then
       Worksheets("STAFFING_VISUAL").Shapes("SinglesPackBUBBLE").Fill.ForeColor.RGB = vbRed
       If Range("'DATA_STAGING'!X27").Value >= 0.7 Or Range("'DATA_STAGING'!X27").Value <= -0.7 Then
            Worksheets("STAFFING_VISUAL").Shapes("SinglesPackBUBBLE").TextFrame.Characters.Text _
            = Round((Worksheets("DATA_STAGING").Range("X27").Value), 0)
        Else
            Worksheets("STAFFING_VISUAL").Shapes("SinglesPackBUBBLE").TextFrame.Characters.Text _
               = 0
        End If
End If

1 个答案:

答案 0 :(得分:1)

如果我理解正确,下面的代码会产生以下“舍入”结果:

 1.8  -->  2
 1.83 -->  2
 1.85 -->  2
 1.7  -->  1
-1.7  --> -1
-1.75 --> -2
-1.8  --> -2

以下是一个例子:

Sub TestRounding()
Dim numbers() As Variant
Dim num As Variant
numbers = Array(1.8, 1.83, 1.85, 1.7, -1.7, -1.75, -1.8)

For Each num In numbers
    Select Case GetMod(CDbl(num))
        Case Is >= 0.8
            Debug.Print num & " --> " & Application.WorksheetFunction.RoundUp(num, 0)
        Case Is <= 0.7
            Debug.Print num & " --> " & Application.WorksheetFunction.RoundDown(num, 0)
        Case Else
            'there should not be anything here because we round num in the GetMod function
    End Select
Next


End Sub
Function GetMod(num As Double) As Double
    num = Round(num, 1) 'to account for anything like 1.74, etc.
    GetMod = Abs(num) - Int(Abs(num))
End Function