Excel VBA通​​过大型计算返回奇怪的结果

bsc*_*fer 2 excel vba

我在excel中创建了一个函数,它基本上在For语句中搜索字符串的动态范围,并返回一列上的单元格的值.它基本上是一个预算编制功能,但这不是重点.

这是问题所在,一切都是小的结果,但是当结果变得太大时(比如大约32000 ......由于某种原因看起来是数字),函数开始返回0.

有没有人有这样的问题?

这是有问题的代码:

Function Material(item As String, Optional sheetType As String) As Integer

Dim wSheet As Worksheetr
Dim count As Integer
Dim offSet As Integer
Dim ref As Integer
Dim bottomRight As Integer
Dim upperLeft As Integer
Dim rng As Range
Dim cVal As Integer

For Each wSheet In Worksheets
    If wSheet.Name = "Drywall Pricing" Then
        dwIndex = wSheet.Index - 1
    End If
Next wSheet

If IsMissing(sheetType) Then
    sheetType = " "
Else
    sheetType = UCase(sheetType)
End If
For i = 1 To dwIndex
    wSheetName = Sheets(i).Name
    If InStr(UCase(wSheetName), sheetType) > 0 Then
        count = 9
        offSet = 44
        ref = 27
        For wall = 0 To count - 1
            On Error Resume Next
            Err.Clear
            upperLeft = (ref + 12) + (offSet * wall)
            bottomRight = (ref + 30) + (offSet * wall)
            Set rng = Sheets(i).Range("A" & upperLeft & ":B" & bottomRight)
            cVal = Application.WorksheetFunction.VLookup(item, rng, 2, False)
            If Err.Number > 0 Then
                cVal = 0
            End If
            units = units + cVal
        Next wall
    Else
        units = units + 0
    End If
Next i

If units > 0 Then
    Material = units
Else
    Material = 0
End If

End Function
Run Code Online (Sandbox Code Playgroud)

我已经设置了一个电子表格来手动计算一定数量的项目(即"= A13 + B5 + B26"等),并将其与运行相关函数的结果进行比较,当结果较低时,它们是彼此相等,所以我知道函数本身工作正常.这是一个记忆问题吗?

任何帮助将不胜感激.

提前致谢!

Rya*_*ndy 12

VBA中的整数是16位,这意味着最大值为32,767(最小值为-32,768).

使用Long来存储结果,而不是Integer,这会在达到限制之前为您提供超过20亿的结果.