VBA Mod, Excel Floor, etc.

L

LesHurley

In VBA, I want to find the fractional part of a number, say N=123.456. The
VBA version of Mod rounds N to an integer before it functions. The
WorksheetFunction Mod() isn't available in VBA. WorksheetFunction.Floor() is
available but it wont work with a negative N. Can anyone suggest how to do
this for any real N?
 
G

Gary''s Student

Sub fracpart()
x = Application.InputBox(prompt:="", Type:=1)
x = Abs(x) - Int(Abs(x))
MsgBox (x)
End Sub

will give the fractional part of both positives and negatives as a positive.
 
B

Bob Phillips

This works as the Excel Mod does

Dim N As Double
Dim remain As Double
Dim sign As Boolean

N = 123.456
sign = N < 0
remain = N - Int(N)
MsgBox remain


--
---
HTH

Bob


(there's no email, no snail mail, but somewhere should be gmail in my addy)
 
L

LesHurley

This works fine for my application but , for future reference, it always
returns a positive fraction.
 
L

LesHurley

-5.4-Round(-5.4,0) = -.4: thats OK but -5.6-Round(-5.6,0) = +.4: Not OK in
general but it would work OK for my particular application since I am testing
if the fractional part is zero.
 
R

Ron Rosenfeld

In VBA, I want to find the fractional part of a number, say N=123.456. The
VBA version of Mod rounds N to an integer before it functions. The
WorksheetFunction Mod() isn't available in VBA. WorksheetFunction.Floor() is
available but it wont work with a negative N. Can anyone suggest how to do
this for any real N?


This should work, including with negative N:

===================
Function vbMod1(N)
vbMod1 = N - Fix(N)
End Function
===================

Due to rounding issues, you probably will want to Round to a specified number
of decimals.
--ron
 
B

Bob Phillips

I transcribed it incorrectly, I really meant

Dim N As Double
Dim remain As Double
Dim sign As Boolean

N = -123.456
sign = N < 0
remain = N - Int(N)
MsgBox IIf(sign, -remain, remain)



--
---
HTH

Bob


(there's no email, no snail mail, but somewhere should be gmail in my addy)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top