VBA函数返回#VALUE!

时间:2011-06-24 13:55:44

标签: vba excel-vba excel

我很困惑为什么以下代码在一个实例中起作用,然后在另一个实例中失败。以下给出#VALUE!错误。

Function RateFetcher(Plan_Text As String, Zip_Text As String, Sex As String, Tabacco_Use As String, Age As Integer, State As String)

Dim Plan As String
Plan = StrConv("Plan " + Plan_Text, vbLowerCase)

Dim ProperState As String
ProperState = StrConv(State, vbProperCase)

Dim Search_Range As Range
Search_Range = Worksheets(ProperState).Range("A4:A600")
MsgBox (Search_Range)

Dim Location As String

For Each c In Search_Range
    If StrConv(c.Value, vbLowerCase) = Plan And c.Offset(1, 0) = Zip_Text Then
        Location = c.Address
    End If
Next c

Dim Sex_Tab_Offset As Integer

Dim Combined As String

Combined = Sex + Tabacco_Use

If Combined = "F NO" Then
    Sex_Tab_Offset = 1
ElseIf Combined = "M NO" Then
    Sex_Tab_Offset = 2
ElseIf Combined = "F YES" Then
    Sex_Tab_Offset = 3
Else
    Sex_Tab_Offset = 4
End If

Dim Age_Offset As Integer
Age_Offset = Age - 65

RateFetcher = Worksheets(ProperState).Range(Location).Offset(Age_Offset, Sex_Tab_Offset).Value
End Function

然而,这是有效的。不同之处在于我明确定义了Search_Range,但我想拥有第一个示例的灵活性,因为那样我就不必定义要搜索的每个范围。要搜索的范围是State_name!$A$4:$A$500

`

 Function RateFetcher(Search_Range As Range, Plan_Text As String, Zip_Text As String, Sex As String, Tabacco_Use As String, Age As Integer, State As String)

Dim Plan As String
Plan = StrConv("Plan " + Plan_Text, vbLowerCase)

Dim ProperState As String
ProperState = StrConv(State, vbProperCase)

'Dim Search_Range As Range
'Search_Range = Worksheets(ProperState).Range("A4:A600")

Dim Location As String

For Each c In Search_Range
    If StrConv(c.Value, vbLowerCase) = Plan And c.Offset(1, 0) = Zip_Text Then
        Location = c.Address
    End If
Next c

Dim Sex_Tab_Offset As Integer

Dim Combined As String

Combined = Sex + Tabacco_Use

If Combined = "F NO" Then
    Sex_Tab_Offset = 1
ElseIf Combined = "M NO" Then
    Sex_Tab_Offset = 2
ElseIf Combined = "F YES" Then
    Sex_Tab_Offset = 3
Else
    Sex_Tab_Offset = 4
End If

Dim Age_Offset As Integer
Age_Offset = Age - 65

RateFetcher = Worksheets(ProperState).Range(Location).Offset(Age_Offset, Sex_Tab_Offset).Value

结束功能 `

1 个答案:

答案 0 :(得分:3)

您希望SetRange的引用,因为Range是一个对象:

Dim Search_Range As Range
Set Search_Range = Worksheets(ProperState).Range("A4:A600")

此外,MsgBox期望参数类型为String,因此您不能MsgBox Range这样。您必须说明要显示的Range的属性,并且我猜您要显示其地址:

MsgBox Search_Range.Address

除此之外,Range的默认属性为Value,因此如果MsgBox Search_Range是对单个单元格的引用,则Search_Range会起作用...但是在您的情况下,Search_Range.Value会返回597个元素的Variant数组,并且不能将其隐式强制转换为String