vba 错误地输入了单个变量的单元格值

vba incorrectly entering cell values from single variable

我的任务是将每个产品的重量输入我们公司的系统(超过 65,000 个),因此我使用 Excel 和对 vba 的有限知识尽可能地实现自动化。

计划是,我输入产品名称的一部分,然后输入要输入的数字,然后在 sheet 上的所有相关行中输入该数字。

问题;我输入的数字很少超过 2 位小数,但是在 sheet 上输入的数字并不相同 - 总是非常接近,但不完全相同。例如,当我试图在相关单元格中输入 0.88 时,它输入了 0.87999995.

代码(简体):

Sub EnterWeight()

Dim Filter As String
Dim Weight As Single

Filter = InputBox("Add text filter", "Add Filter")

w = InputBox("Insert weight in Kg", "Enter Weight", 1) 
'(yes, I know it should be 'mass in Kg', but ... ¯\_(ツ)_/¯ )

Weight = CDec(w)

Debug.Print Weight 'To test that it's the correct number, always seems to be ok.

    For b = 1 To Activesheet.UsedRange.Rows.Count
        If Cells(b, ) Like "*" & Filter & "*" Then 'Find the filter in any part of the cell

            If Cells(b, 2) <> "" And Cells(b, 2).Value <> SG Then 'Cells already populated with a different value

            y = MsgBox("Product """ & Cells(b, 1).Value & _
                """ already has a weight assigned of " & _
                Cells(b, 2).Value & Chr(13) & _
                "OverWrite?", vbYesNo + vbExclamation, _
                "Weight already assigned")
                If y = vbYes Then Cells(b, 2).Value = Weight

            Else
                Cells(b, 2).Value = Weight
            End If

        End If

    Next
End sub

谁能告诉我为什么不能在相关单元格中正确输入 Weight 变量?搜索 google 似乎没有产生答案,尽管也许我只是问错了。

非常感谢

这个问题可以最小化为:

Sub test1()
    Dim Weight As Single
    Weight  = InputBox("Insert weight in Kg", "Enter Weight", 1)
    Cells(2, 2).Value = Weight
End Sub

在输入框中输入“.88”会使单元格接收到“0.879999995231628”

但是,将 Weight 更改为 Double:

Sub test2()
    Dim Weight As Double
    Weight  = InputBox("Insert weight in Kg", "Enter Weight", 1)
    Cells(2, 2).Value = Weight
End Sub

在输入框中输入“.88”会使单元格接收到“0.88”


查看 VBA Double vs Single rounding 的答案,详细解释为什么会发生这种情况。