我在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”等),并将其与运行相关功能的结果进行比较,结果是低,它们彼此相等,所以我知道函数本身工作正常。这是一个记忆问题吗?
非常感谢任何帮助。
提前致谢!
答案 0 :(得分:12)
VBA中的整数是16位,这意味着最大值为32,767(最小值为-32,768)。
使用Long来存储你的结果,而不是Integer,这会在你达到限制之前为你提供超过20亿的结果。
答案 1 :(得分:0)
您可以发布要搜索的Excel文档内容的摘录吗?
两条小评论:
就行了
If wSheet.Name = "Drywall Pricing" Then
dwIndex = wSheet.Index - 1
End If
您可能希望Exit For
找到工作表,但又不想继续搜索。
您是否有任何理由想要找到的表单MINUS 1?
另一条评论是units = units + 0
- Else
条款中没有任何内容。
问候
答案 2 :(得分:0)
在VBA中,“Integer”不是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
另外,我建议使用“Option Explicit”。
答案 3 :(得分:0)
整数的最大值是(2 ^ 15),即32,768。您的错误捕获是强制cVal = 0.尝试将数据类型从整数更改为long。 Max Long为(2 ^ 31 -1),即2,147,483,647,应该可以轻松处理您的值。