如何使用instr检查vba中是否有任何字符前面的数字

时间:2015-09-25 17:42:34

标签: vba excel-vba excel

问题描述:找一个instr(这是数字),然后检查instr值是否带有前面的任何字符。(例如123,x123)。如果带有字符的instr或instr与表2中的值匹配,则msg框为yes。

问题:我可以找到instr但是我无法检查instr是否包含任何char前面。我如何检查它,是左(chr)功能还是其他东西。这是我的代码,但所有这些只是通过instr找到instr而不是chr。

enter image description here enter image description here

Sub tym()

    Dim ws1 As Worksheet, wb As Workbook, ws2 As Worksheet
    Dim b, c As Range, rngNums As Range, rngText As Range
    Dim dNums, dText, rN As Long, rT As Long, t, m

    Set wb = ActiveWorkbook
    Set ws1 = wb.Worksheets("Sheet1")
    Set ws2 = wb.Worksheets("Sheet2")
    Set c = wb.Worksheets("Sheet3").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)

    Set rngNums = ws1.Range(ws1.Range("A1"), ws1.Cells(Rows.Count, 1).End(xlUp))
    dNums = rngNums.Value
    Set rngText = ws2.Range(ws2.Range("A1"), ws2.Cells(Rows.Count, 1).End(xlUp))
    dText = rngText.Value

    For rN = 1 To UBound(dNums, 1)
        b = "-" & dNums(rN, 1) & "-" (right here im defining to find instr but how do i add a function to find char front of instr)
        For rT = 1 To UBound(dText, 1)
            If InStr(1, dText(rT, 1), b) > 0 Then

               MsgBox "yes"

            End If
        Next rT
     Next rN

End Sub

1 个答案:

答案 0 :(得分:1)

您可以使用

测试破折号之间是否存在非数字字符
If "xxx-x123-xxx" Like "*-[!0-9]-*" Then

编辑:如果你只是想检查有问题的数字,每边都有非数字字符,那么:

Dim v, p

v  = 123
p = "*[!0-9]" & v & "[!0-9]*"

If "xxx-x123-xxx" Like p Then 
    'matched pattern...
End If