我怎样才能find确切的Instr价值

我试图find确切的数字,而不是find整数。 像这样的456678 。 每次当我运行我的代码,我最终find整个数字( 45677777 ),而不是只有456 。 为了说清楚,我在同一行中有几个数字,例如( 456,456777777,677,456,456666666等)。 我正在试图让我的InStr避免与4567777号码。

在这里输入图像说明

代码

  dim b as string b = "-456-" for i = 1 to lastrow if instr( 1, worksheets("sheet1").range("A" & i), b > 0 then msgbox yes end if next i 

如果需要精确匹配而不是InStr,则应使用=运算符进行比较。

  b = "456" For i = 1 To 7 If (b = Cells(1, i).Value) Then Debug.Print ("Yes") Else Debug.Print ("No") End If Next i 

如果您试图testing的值有连字符,那么在进行任何比较之前,您必须将其parsing出来。

另外,如果你正在使用范围,我发现导入范围到数组中,并使用数组而不是实际的单元格和它们的值更容易,也更快。 编辑:为了使它更加dynamic,所以你不必硬编码你正在寻找的范围是什么,你希望子做这个,直到没有值看在列中了,你可以使用Find方法。

这将适用于您的示例,如下所示:

 Dim arrVals() lastrow = Cells.Find("*", , xlValues, , xlByRows, xlPrevious).Row strRangeToCapture = "A1:A" & CStr(lastrow) arrVals = Range(strRangeToCapture) Dim b As String b = "456" For i = 1 To lastrow If (b = arrVals(i, 1)) Then Debug.Print ("Yes") Else Debug.Print ("No") End If Next 

希望这可以帮助! 🙂

你的示例数据不会显示它,但从你的描述,它听起来像你有单元格中的逗号分隔值。

拆分单元格中的值,然后查看每个值以确切匹配。

 ColumnA --------------------- 444, 456777, 456, 888 777 444, 456777, 444, 888 456 

这将只能find行1和4。

 Private Sub CommandButton5_Click() Dim lRow As Long Dim ws As Excel.Worksheet Dim strValues() As String Dim i As Integer Dim b As String b = "456" Set ws = Application.ActiveSheet 'Loop through all the rows. lRow = 1 Do While lRow <= ws.UsedRange.Rows.Count 'Get the values strValues = Split(ws.Range("A" & lRow).Value, ",") For i = 0 To UBound(strValues) If strValues(i) = b Then MsgBox ("Row " & Str(lRow) & " has a match.") End If Next i lRow = lRow + 1 Loop End Sub 

从MSDN, InStr

返回一个整数,指定在另一个string中第一次出现的起始位置

所以你所观察到的是这个函数的正确行为。
为了得到你想要的东西,你可以使用Richard发布的内容或者自从使用Excel之后,可以尝试使用范围对象的Find方法,这对于大型数据集在速度方面有一些好处。

就像是:

 Dim r As Range, found As Range Dim b As String, FAdd As String Dim lastrow As String With Worksheets("Sheet1") lastrow = .Range("A" & .Rows.Count).End(xlUp).Row Set r = .Range("A1:A" & lastrow): b = "456" Set found = r.Find(b, .Range("A" & lastrow) , , xlWhole) End With If Not found Is Nothing Then FAdd = found.Address Else MsgBox "No match found.": Exit Sub Do Debug.Print found.Address Set found = r.FindNext(After:=found) Loop While FAdd <> found.Address 

尝试这种方法:

数据样本:

在这里输入图像说明

代码:

 Sub test() Dim cl As Range, key As Variant, Data As Range, criteria$ criteria = "456" Set Data = Range([A1], Cells(Cells(Rows.Count, "A").End(xlUp).Row, "A")) For Each cl In Data For Each key In Split(cl.Value, ",") If Trim(key) = criteria Then MsgBox "Row: " & cl.Row & " has a value: " & cl.Value & " matched with search string" End If Next key Next cl End Sub