【发布时间】:2020-03-12 13:28:59
【问题描述】:
我的任务是在我们公司的系统中输入每件产品的重量(超过 65,000 个),所以我使用 Excel 和稍微有限的 vba 知识来尽可能自动化。
计划是,我输入产品名称的一部分,然后输入要输入的数字,然后在工作表的所有相关行中输入该数字。
问题;我输入的数字很少超过小数点后 2 位,但是在工作表上输入的数字并不相同 - 总是非常接近,但不完全一样。例如,当我刚刚尝试在相关单元格中输入 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 变量?通过谷歌搜索似乎没有得到答案,虽然也许我只是问错了。
提前致谢
【问题讨论】:
-
更改单元格的
.NumberFormat?旁注 - 你为什么在这里CDecing,为什么weight是Single?个人会一直使用Double。 -
并使用
Application.InputBox而不是InputBox。 -
谢谢...嗯,
Cdec是我徒劳地尝试过的东西,以防它解决了问题,结果它实际上并没有做任何事情。这不是我所关心的单元格的格式(对我来说它的外观没有区别),但它会影响稍后在该单元格上发生的计算。至于单/双辩论 - 没有理由,我只知道“双”是为了更准确的事情而制作的,我不需要那种准确性。 -
您介意解释一下
application.inputbox会有什么不同吗? -
可以指定输入的
Type。
标签: excel vba variable-types