excel - 如何在VBA中比较数字到一定的小数位数?
问题描述
我有下面的代码来比较同一工作簿中两个不同工作表的值,但我只需要比较到小数点后 2 位,即 123.45 而不是 123.4568786。有没有办法指定十进制值的数量进行比较?
difference = 0
For col = 1 To maxcol
For row = 1 To maxrow
colval1 = ""
colcal2 = ""
colval1 = Ws1.Cells(row, col)
colval2 = Ws2.Cells(row, col)
If colval1 <> colval2 Then
difference = difference + 1
Cells(row, col) = colval1 & "<>" & colval2
End If
Next row
Next col
这是代码的输出:
编辑:我声明colval1
andcolval2
为 Double,但我仍然得到“类型不匹配”,但使用这一行colval1 = Ws1.Cells(row, col)
difference = 0
For col = 1 To maxcol
For row = 1 To maxrow
colval1 = 0
colcal2 = 0
colval1 = Ws1.Cells(row, col)
colval2 = Ws2.Cells(row, col)
If WorksheetFunction.Round(colval1, 2) <> WorksheetFunction.Round(colval2, 2) Then
difference = difference + 1
Cells(row, col) = colval1 & "<>" & colval2
End If
Next row
Next col
解决方案
You can use the VBA's round function which returns the rounded number based on the specified number of decimal places
If Round(colval1, 2) <> Round(colval2, 2) Then
difference = difference + 1
Cells(Row, col) = Round(colval1, 2) & "<>" & Round(colval2, 2)
End If
or
colval1 = Round(Ws1.Cells(Row, col), 2)
colval2 = Round(Ws2.Cells(Row, col), 2)
If colval1 <> colval2 Then
difference = difference + 1
Cells(Row, col) = colval1 & "<>" & colval2
End If
regarding the right annotation of @BigBen, we can define a small function that returns the desired value without rounding
Public Function Round2(Num As Variant, Decimals As Variant) As Variant
Round2 = IIf(IsNumeric(Num) And IsNumeric(Decimals), Int(Num * 10 ^ Decimals) / 10 ^ Decimals, CVErr(xlErrValue))
End Function
推荐阅读
- php - 每个字段上的 Symfony 动态表单
- reactjs - 使用 axios 的 Reactjs POST 请求
- angularjs - D3js / AngularJS - 拖动和数据绑定矩形的坐标
- text - 如何拆分日文文本?
- react-native - React 本机 af-video-player 提供没有 proptype
- php - 联系表格 7 - Wordpress
- webview - 当询问页面请求方法是否为 POST 时,UWP WebView 控件不刷新
- reactjs - 如何在移动状态中的项目或使用地图呈现的道具时添加过渡
- php - 如何避免 HTTP 标头注入攻击
- node.js - 升级到 Gulp 4 时发出异步完成警告