-1

In the code below, why do I get an overflow error at x = i ^ 3 ?

    Dim i As Long, x As Long, s As Long, k As Byte

    Do
        i = i + 1
        x = i ^ 3

    Dim n As Long, j As Long, b As String
        b = CStr(x)
        n = Len(b)
        For j = 1 To n
            s = s + Val(Mid$(b, j, 1))
        Next

        If s = i Then
            k = k + 1
            Debug.Print i
        End If
    Loop Until k = 6

When I take out the part of code that starts with Dim n as long and ends with the for loop, and turn it into an auxiliary function, then the remaining code works (that is, no overflow error at x = i ^ 3).

4
  • 1
    Your code is so obscure that it is hard to see just how much i is incremented. There is a limit to the size of a number that a Long can hold. Once i exceeds 1290, i^3 overflows a long. In my response to your other question I suggested that you need to use the decimal subtype of a variant to do what you seem to be trying to do. That recommendation still holds. Jul 7, 2016 at 1:02
  • Also -- note that you are never resetting s in successive passes through the loop. If your intention is to get the sum of the digits in x then maybe you should rest s to 0 before the for loop. Jul 7, 2016 at 1:11
  • Your comment that I need to reset s to 0 before the loop, I think that solves my problem. Thanks again!
    – TylerC
    Jul 7, 2016 at 1:12
  • 1
    You are mistaken. When I run your code I get the same overflow error. Hovering the cursor over the i reveals that its value when the error is triggered is 1291. Jul 7, 2016 at 1:16

1 Answer 1

0

The Data Type Summary (Visual Basic) - MSDN - Microsoft are not the data types used in the VBA VBA Data Types

Visual Basic Long is 8 bytes with a min/max value of -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807.

VBA Long is 4 bytes with a min/max value of -2,147,483,648 to 2,147,483,647.

1291 ^ 3 = 2,151,685,171 'Runtime Error 6 Overflow

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.