VBA not calculating how I want it to

  • Thread starter Thread starter dmatador
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 2K views
dmatador
Messages
120
Reaction score
1
I've just been messing around on VBA and am trying to write a summation that estimates pi. It doesn't add anything to the sum within the do while. I tried a for loop also, but it just takes whatever i initialize sum to and multiplies it by 4 and adds one. I just want it to add continually to sum the new values of n given j. Need help it seems like such a simple problem...


Sub pi()
Dim j As Integer
Dim sum As Integer
Dim n As Integer

sum = 0
j = 2

Do While j <= 100
n = (1 / (2 * j - 1)) * ((-1) ^ (2 * j - 1))
sum = sum + n
j = j + 1
Loop
sum = 4 * sum + 1
Range("E2:E100").Cells(2).Value = sum

End Sub
 
Last edited:
Physics news on Phys.org
dmatador said:
I've just been messing around on VBA and am trying to write a summation that estimates pi. It doesn't add anything to the sum within the do while. I tried a for loop also, but it just takes whatever i initialize sum to and multiplies it by 4 and adds one. I just want it to add continually to sum the new values of n given j. Need help it seems like such a simple problem...


Sub pi()
Dim j As Integer
Dim sum As Integer
Dim n As Integer

sum = 0
j = 2

Do While j <= 100
n = (1 / (2 * j - 1)) * ((-1) ^ (2 * j - 1))
sum = sum + n
j = j + 1
Loop
sum = 4 * sum + 1
Range("E2:E100").Cells(2).Value = sum

End Sub

Your variables sum and n should not be declared as integer. There might be other problems in your code, but this jumped out at me right away.