类型不匹配错误instr

时间:2015-05-04 06:16:17

标签: excel vba excel-vba

我想在保单持有人(NRIC)中找到IC号码。但是代码中存在错误。

    Dim col As Long
    Dim IC, NRIC
    Dim name

    name = ActiveSheet.Cells(rw, 1).Value

    NRIC = ThisWorkbook.Sheets("main").Columns(9)

    IC = InStr(1, name, "(" & NRIC & ")") <<<<< this is the problem (type mismatch error)

    MsgBox IC

显示:

主要表

名称列

  • 雪利酒

IC栏

  • S1233456c

policydetails表

policyowner(NRIC)专栏

  • 雪利酒(S1233456c)

1 个答案:

答案 0 :(得分:1)

InStr Function第三个参数需要一个字符串( substring ) 你实际上传递了一个数组,它是整个Column(9) 要使它工作,你需要遍历Column(9)中的所有值,如下所示:

Dim c As Range
With ThisWorkbook.Sheets("main")
    For Each c In .Columns(9).CurrentRegion
        If InStr(1, name, c.Value2) <> 0 Then
            MsgBox c.Value2 ' I don't know what you want to do if you find the cell
            Exit Sub
        End If
    Next
End With

另一种方法是使用范围对象的Find Method

Dim c As Range
With ThisWorkbook.Sheets("main")
    Set c = .Columns(9).CurrentRegion.Find(What:=name, LookAt:=xlPart)
    If Not c Is Nothing Then MsgBox c.Value2
End With