Instr函数,找到整数,所以12对于1不会返回true

时间:2016-11-09 17:30:27

标签: excel vba

我试图找到一种方法来搜索单元格中可能已输入的数字。 所以B2的值是12.当使用Instr时它会找到1,2和12.有没有办法让它只返回12?这是我目前正在使用的代码,如果我只使用1-9就可以,但是我需要更多选项。

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

3 个答案:

答案 0 :(得分:1)

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

您可以先用逗号分割输入字符串(将其保存到数组中),然后遍历该数组中的每个数字并检查它是否包含该值:

value was not declared in this scope

答案 1 :(得分:1)

一些问题:

  • 当内容是以逗号分隔的列表时,测试IsNumeric不会产生True,在这种情况下,它将具有字符串数据类型。
  • 变量PRTVal被声明为字符串,但您在其上使用+运算符。那应该是&

您可以使用Split通过逗号分隔符拆分字符串,然后循环显示部分。

以下是适应的部分:

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

答案 2 :(得分:0)

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

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

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