【问题标题】:Excel VBA returning weird results with large calculationsExcel VBA 通过大量计算返回奇怪的结果
【发布时间】:2009-09-18 20:37:33
【问题描述】:

我在 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

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

任何帮助将不胜感激。

提前致谢!

【问题讨论】:

  • 你为什么不调暗单位?
  • 不...这是我的错误。

标签: excel vba


【解决方案1】:

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

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

【讨论】:

  • 嗯,这对于停止在 32,000 左右的数字来说很有意义。感谢您的快速回复!我马上改。
【解决方案2】:

您可以将要搜索的 excel 文档的内容摘录出来吗?

两个小cmets:

上线

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

您可能想Exit For,因为您找到了您的工作表并且不想继续搜索。

你有什么理由想要找到的工作表 MINUS 1?

另一条评论是Else子句中的units = units + 0什么都不做。

问候

【讨论】:

  • 是的。所有材料表都在“石膏板定价”表之前,因此“石膏板定价”表索引 MINUS 1 的索引号将为我提供该功能需要扫描的表总数。此外,units = units + 0 是对我的保留,但我无法告诉你为什么我一开始就有它。
【解决方案3】:

在 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

另外,我建议使用“选项显式”。

【讨论】:

    【解决方案4】:

    整数的最大值是 (2^15),即 32,768。您的错误捕获迫使 cVal = 0。尝试将数据类型从整数更改为长整数。 Max Long 是 (2^31 -1),即 2,147,483,647,应该可以轻松处理您的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-08
      • 2012-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多