开发者

Out of stack space in vba when running code for project euler #1

Option Explicit
Sub peuler1()
Dim x As Variant
Dim y As Variant
y = 0
For x = 1 To 999
    If x Mod 3 = 0 Or x Mod 5 = 0 Then
    y = y + x
    End If
Next x
Call peuler1
End Sub

Why is this taking so long? it doesn't seem开发者_StackOverflow中文版 to be too convoluted.


I believe you are in a recursive loop.

Remove Call peuler1


You are calling your subroutine from within itself. That's going to give you an infinite loop.


Because you seem to call function peuler1 inside its definition, you then keep going recursively until you fill up stack space.

(I don't use visual basic, just a guess)


How about this?

Option Explicit 
Function peuler1() as integer
   Dim x As integer
   Dim y As integer 
   y = 0 
   For x = 1 To 999 
      If x Mod 3 = 0 Or x Mod 5 = 0 Then y = y + x 
   Next x 
   pueler1=y
End Sub 

This procedure is a function, which means it returns a value (Subs do stuff. Functions calculate something). Adding peuler1=y at the bottom makes the function return the value of y. The advantage of this is that you can now call this procedure from another procedure.

If you are working on this in the standard MS Office VBA Editor, you can get your answer by typing debug.print peuler1 in the Immmediate window.


Move the Call peuler1 outside of the End Sub. You're calling peuler1 when you get to the end of peuler1, and never get to the end of it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜