Forum

return a value of F...
 
Notifications
Clear all

return a value of Function and use it in macro

2 Posts
2 Users
0 Reactions
101 Views
(@dorsa)
Posts: 1
New Member
Topic starter
 

I write a macro that have a function for calculating the factorial of numbers.

and I want call it in my sub and return the value of that factorial function in a cell in my sheet. but when I run my macro it just return 0 to me.

this is my code:

 

Function Factorial(x As Integer) As Integer

Dim i As Integer

Dim F As Integer

F = 1

For i = 1 To x

Factorial = Factorial * i

Next i

End Function

******

Sub macro1()

Dim j, k As Integer

For j = 2 To 8

u = (10) ^ (-7 + j) Cells(j, 3).Value = u Cells(j, 6).FormulaR1C1 = _ "=-0.5772-LN(RC[-3])+RC[-3]-((RC[-3]^2)/(2*FACT(2)))+((RC[-3]^3)/(3*FACT(3)))-((RC[-3]^4)/(4*FACT(4)))"

Next j

Cells(8, 8) = Factorial(3)

End Sub

 

my function is work truely but when I want to call it return the 0.how can I solve my problem?

 
Posted : 03/04/2019 4:46 pm
Philip Treacy
(@philipt)
Posts: 1630
Member Admin
 

Hi Dorsa,

You start working out the factorial using an uninitialized variable 'Factorial' which has a default value of 0.  So your function result is always 0

Using basic debugging you could have discovered this easily 🙂

Read up on debugging with these articles

Debugging VBA

More Tips for Debugging VBA

 

Here's the working function

 

  Function Factorial(x As Integer) As Integer

    Dim i As Integer

    Dim F As Integer

    F = 1

    For i = 1 To x

      F = F * i

    Next i

    Factorial = F

  End Function

 

Regards

Phil

 
Posted : 03/04/2019 9:39 pm
Share: