数据类型不匹配错误,即使数据类型相同

时间:2015-11-03 15:43:46

标签: excel-vba runtime-error vba excel

任何人都可以告诉我为什么我会得到"运行时错误13:类型不匹配"在下面的代码? cell2和lookupvalues变量都是变量数据类型,所以我不确定问题是什么。

Sub MULTVLOOKUP()

    Dim lookupvalues As Variant
    Dim lookuprange As Range
    Dim returnrange As Range
    Dim cell As Variant
    Dim cell2 As Variant

    lookupvalues = Application.InputBox(Prompt:="What value do you want to      search for?", Title:="lookupvalue", Type:=8)
    Set lookuprange = Application.InputBox("What range do you want to search for this value in?", "lookuprange", Type:=8)
    Set returnrange = Application.InputBox("What cell do you want the results to begin being returned at?", "returnrange", Type:=8)

    For Each cell In lookupvalues
        For Each cell2 In lookuprange
            If InStr(1, cell2, lookupvalues) > 0 Then
                returnrange = cell2
                Set returnrange = returnrange.Offset(1, 0)
            End If
        Next
    Next

End Sub

仅供参考,我希望此宏从用户定义的范围(lookuprange)返回单元格值,该范围满足用户也定义的多个条件之一(lookupvalues)。然后从用户定义的范围(返回范围)开始返回适用的单元格值。所有这些用户输入都通过输入框完成。当用户只选择一个条件时,我已经让宏工作了,但我一直在尝试修改代码,以便可以选择多个条件/单元格。错误发生在这一行:

If InStr(1, cell2, lookupvalues) > 0 Then

非常感谢你的帮助!!

1 个答案:

答案 0 :(得分:0)

根据我的评论,这是我对你正在尝试的最佳猜测

Sub MULTVLOOKUP()

    Dim lookupvalues As Range
    Dim lookuprange As Range
    Dim returnrange As Range
    Dim cell As Variant
    Dim cell2 As Variant

    Set lookupvalues = Application.InputBox(Prompt:="What value do you want to      search for?", Title:="lookupvalue", Type:=8)
    Set lookuprange = Application.InputBox("What range do you want to search for this value in?", "lookuprange", Type:=8)
    Set returnrange = Application.InputBox("What cell do you want the results to begin being returned at?", "returnrange", Type:=8)

    For Each cell In lookupvalues
        For Each cell2 In lookuprange
            If InStr(1, cell2, cell.Value) > 0 Then
                returnrange = cell2
                Set returnrange = returnrange.Offset(1, 0)
            End If
        Next
    Next

End Sub