Excel VBA以大量计算返回奇怪的结果

我在Excel中创build了一个函数,它基本上在For语句中为一个stringsearch一个dynamic范围,并返回一列的单元格的值。 这基本上是一个预算function,但是这不重要。

这是一个问题,一切工作的结果都很小,但是当结果变得太大时(比如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 

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

任何帮助将不胜感激。

提前致谢!

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

使用Long来存储结果,而不是整数,在结果达到20亿之前,它会达到极限。

你可能会张贴被search的excel文件的内容摘录吗?

两点意见:

在线上

 If wSheet.Name = "Drywall Pricing" Then dwIndex = wSheet.Index - 1 End If 

您可能希望Exit For因为您已经find了工作表,而且您不想继续search。

是否有任何理由你想find的工作表减MINUS 1?

另一种说法是,在Else语句中, units = units + 0什么也不做。

问候

在VBA和“整数”是不是一个整数16位? 即,-32,768至+32,767? 如果是的话,那么这里的代码是你的罪魁祸首:

 Dim cVal As Integer ... cVal = Application.WorksheetFunction.VLookup(item, rng, 2, False) If Err.Number > 0 Then cVal = 0 End If 

另外,我会build议使用“Option Explicit”。

整数的最大值是(2 ^ 15),即32,768。 您的错误捕获强制cVal = 0.尝试将数据types从整数更改为长。 Max Long是(2 ^ 31 -1),它是2,147,483,647,应该很容易处理你的值。