简体   繁体   中英

Run-time error 6: Overflow: Excel VBA

I have been trying to resolve this but could not. I have the following VBA code. While running it gives "run time error 6: Overflow". I guess I have assigned a right type to each variable. Please help!!

Sub UseCoeff()
Dim a, b As Long
Dim Value1 As Double

ThisWorkbook.Sheets("UseTableBEA").Activate
For b = 2 To 427
    For a = 2 To 431

        Value1 = ThisWorkbook.Sheets("UseTableBEA").Cells(a, b).Value / ThisWorkbook.Sheets("UseTableBEA").Cells(432, b).Value
        ThisWorkbook.Sheets("UseCoeff").Cells(a, b).Value = Value1

    Next a
Next b
End Sub

Each cell will have a result that may be between 0 and 1 up to eight decimal places. Thanks in advance!!

If ThisWorkbook.Sheets("UseTableBEA").Cells(432, b).Value is ever 0, then ThisWorkbook.Sheets("UseTableBEA").Cells(a, b).Value / ThisWorkbook.Sheets("UseTableBEA").Cells(432, b).Value will cause the Overflow error if ThisWorkbook.Sheets("UseTableBEA").Cells(a, b).Value is also 0.

To avoid this, use an if statement to filter out the 0s, just update the comment with the actual logic you want:

If ThisWorkbook.Sheets("UseTableBEA").Cells(432, b).Value = 0 Then
    Value1 = 'Whatever you want but probably 0.
Else
    Value1 = ThisWorkbook.Sheets("UseTableBEA").Cells(a, b).Value / ThisWorkbook.Sheets("UseTableBEA").Cells(432, b).Value
End If

Dim a, b As Long

a is not declared as a long it is declared as a variant try this:

Dim a as long, b as Long

Edit: Having tested this, it still produces a Stack Overflow error. However it is good practice to declare your variables properly.

You also don't need this line:

ThisWorkbook.Sheets("Sheet1").Activate

and if you declare UseTableBEA you can slim down your code:

Dim Ws1 as Worksheet
Set Ws1 = Sheets("UseTableBEA")

You can then use Ws1 where you have previously used ThisWorkbook.Sheets("UseTableBEA")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM