类型不匹配错误instr

类型不匹配错误instr

问题描述:

我想找到策略所有者(NRIC)中的IC号码。但代码中存在错误。类型不匹配错误instr

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)

InStr Function第三参数需要字符串()。
你实际上传递了一个数组,它是整个Column(9)。
对于它的工作,你完成所有的列(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