3

我一直在尝试解决这个问题,但无法解决。我有以下 VBA 代码。运行时出现“运行时错误 6:溢出”。我想我已经为每个变量分配了正确的类型。请帮忙!!

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

每个单元格的结果可能介于 0 和 1 之间,最多八位小数。提前致谢!!

4

2 回答 2

3

如果ThisWorkbook.Sheets("UseTableBEA").Cells(432, b).Value曾经为 0,那么如果也是 0,ThisWorkbook.Sheets("UseTableBEA").Cells(a, b).Value / ThisWorkbook.Sheets("UseTableBEA").Cells(432, b).Value则会导致溢出错误ThisWorkbook.Sheets("UseTableBEA").Cells(a, b).Value

为避免这种情况,请使用 if 语句过滤掉 0,只需使用您想要的实际逻辑更新注释:

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
于 2012-09-18T04:18:43.930 回答
2

Dim a, b As Long

a 未声明为 long 它被声明为变体试试这个:

Dim a as long, b as Long

编辑: 经过测试,它仍然会产生堆栈溢出错误。但是,正确声明变量是一种很好的做法。

您也不需要这一行:

ThisWorkbook.Sheets("Sheet1").Activate

如果你声明UseTableBEA你可以精简你的代码:

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

然后Ws1,您可以在以前使用过的地方使用ThisWorkbook.Sheets("UseTableBEA")

于 2012-09-18T12:47:48.523 回答