OK, so using the fact that the worksheet MOD function can be expressed in terms of the INT function:
MOD(n, d) = n - d*INT(n/d)
(from the Excel help file)
I re-wrote the UDF like this:
Function DecTo32Bin(Dec As Double)
' Function to return the binary representation of a 32-bit integer as a string' in the format "00000000.00000000.00000000.00000000"' Input must be a positive integer between 0 and 4,294,967,295 inclusive.'
Dim str1 As String, str2 As String, str3 As String, str4 As String
Dim d As Double, n As Double
d = 256
n = Dec / (2 ^ 24) '16777216
str1 = Application.WorksheetFunction.Dec2Bin((n - d * Int(n / d)), 8)
n = Dec / (2 ^ 16) '65536
str2 = Application.WorksheetFunction.Dec2Bin((n - d * Int(n / d)), 8)
n = Dec / (2 ^ 8) '256
str3 = Application.WorksheetFunction.Dec2Bin((n - d * Int(n / d)), 8)
n = Dec
str4 = Application.WorksheetFunction.Dec2Bin((n - d * Int(n / d)), 8)
DecTo32Bin = str1 & "." & str2 & "." & str3 & "." & str4
End Function
This now appears to work ok. I'm left with 2 questions:
1) Why didn't my original UDF work?
2) In my re-written UDF, should "d" and "n" be declared as Doubles, or something else?
Cheers
Rich
[EDIT: Perhaps I spoke too soon. Works ok except with 2147483648 or above as the input. This should return 10000000.00000000.00000000.00000000 but instead returns the #NUM! error.
Please help!]
[EDIT2: OK, fixed that too by changing the first line of the function from:
Function DecTo32Bin(lnDec As Long)
to
Function DecTo32Bin(Dec As Double)
BUT doing that to my original UDF didn't fix it, so my questions still stand..]