Instr函数,查找整个数字,所以12不会返回true

我正试图find一种方法来search单元格可能已被input的数字。 所以B2的值是12.当使用Instr时,它会发现1,2和12.有没有办法让它只返回12? 这里是我目前正在使用的代码,如果我只使用1-9将罚款,但我需要更多的select。

Sub PRTLookup() Dim WsP As Worksheet Dim PRTval As String Dim MonCt As Long, DayCT As Long Set WsP = ThisWorkbook.Sheets("PT") For MonCt = 2 To 46 Step 4 For DayCT = 2 To 32 CelVal = Cells(MonCt, DayCT) If IsNumeric(CelVal) Then For x = 1 To 26 If InStr(Cells(MonCt, DayCT).Text, x) Then PRTval = PRTval + WsP.Cells(x, 1).Value Next Cells(MonCt, DayCT).Value = PRTval PRTval = Empty End If Next Next End Sub 

这是为我工作的最终代码:

 Dim myarr() as string Dim num as Variant For MonCt = 2 To 46 Step 4 For DayCT = 2 To 32 Celval = Cells(MonCt, DayCT) myarr = Split(Celval, ",") For Each num In myarr PRTval = PRTval & " " & WsP.Cells(num, 1).Text Next num Cells(MonCt, DayCT).Value = PRTval PRTval = Empty Next Next 

我不是很了解你的问题,但这是我的想法:

您可以先用逗号分隔inputstring(将其保存到数组中),然后迭代该数组中的每个数字并检查它是否包含值:

 Dim myarr() as String Dim num as String myarr = Split(inputLine, ",") For each num in myarr ...... Next num 

一些问题:

  • 当内容是逗号分隔列表时,testingIsNumeric将不会产生True ,在这种情况下,它将具有String数据types。
  • variablesPRTVal被声明为一个string,但是你使用+运算符。 这应该是&

您可以使用Split通过逗号分隔符分割string,然后您可以循环部分。

这里是适应的部分:

 Dim nums As String Dim str As Variant ' ... etc ... If IsNumeric(Replace(Replace(CelVal, ",", ""), " ", "")) Then PRTval = "" nums = Split(CelVal, ",") For Each str In nums x = CInt(str) If x >= 1 And x <= 26 Then PRTval = PRTval & ", " & WsP.Cells(x, 1).Value Next Cells(MonCt, DayCT).Value = Mid(PRTval, 3) ' skip first ", " End If 

您可以先查找一个数字,然后检查下一个字符是否也是一个数字。 所以只要没有更多的数字就可以迭代。

更新:我会做这样的事情:

 For i = 1 To Len(myString) j = 0 If IsNumeric(Mid(myString, i, 1)) Then Do While IsNumeric(Mid(myString, i, 1 + j)) And i + j <= Len(myString) j = j + 1 Loop output = Mid(myString, i, j) MsgBox output End If i = i + j Next i