[英]VBA equivalent to Excel's mod function
是否有一個 vba 相當於 excel 的mod
function?
我在VBA中復制Excel的MOD(a,b)
在VBA中使用XLMod(a,b)
,其中包含函數:
Function XLMod(a, b)
' This replicates the Excel MOD function
XLMod = a - b * Int(a / b)
End Function
在您的VBA模塊中
使用Excel MOD(a,b)函數和VBA和Mod b運算符時要非常小心。 Excel返回浮點結果,VBA返回整數。
在Excel = Mod(90.123,90)中返回0.123000000000005而不是0.123在VBA中90.123 Mod 90返回0
他們當然不等同!
相當於:在Excel中:= Round(Mod(90.123,90),3)返回0.123和In VBA :((90.123 * 1000)Mod 90000)/ 1000返回也是0.123
最佳答案實際上是錯誤的。
建議的等式: a - (b * (a \\ b))
將解決: a - a
在所有情況下,當然是0。
正確的等式是:
a - (b * INT(a \\ b))
或者,如果數字(a)可能是負數,請使用:
a - (b * FIX(a \\ b))
但是,如果您只是想區分奇數迭代和偶數迭代之間的區別,這可以正常工作:
If i Mod 2 > 0 then 'this is an odd
'Do Something
Else 'it is even
'Do Something Else
End If
Function Remainder(Dividend As Variant, Divisor As Variant) As Variant
Remainder = Dividend - Divisor * Int(Dividend / Divisor)
End Function
此功能始終有效,並且是Excel功能的精確副本。
最初甚至 XLMod = (a - (b * Int(a / b))) 也給我不正確的結果所以..
Function XLMod(a, b As Long)
' This replicates the Excel MOD function - the VBA mod function returns an integer
Dim templong As Long
templong = (b * Int(a / b))
XLMod = (a - templong)
End Function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.