简体   繁体   English

搜索数字和度数符号

[英]Search for number and degree symbol

I have a worksheet that needs to classify elbows based on their degrees but also has a lot of other material in it.我有一个工作表,需要根据肘部的度数对其进行分类,但其中还有很多其他材料。 I'm using VBA.我正在使用 VBA。 I can't just use a Like or InStr function to search 45, 90, etc. because it is returning other material.我不能只使用 Like 或 InStr 函数来搜索 45、90 等,因为它正在返回其他材料。 I have used the following to find the degree symbol and the number but it is returning values if they occur in the cell at all, not necessarily if they are right next to each other.我已经使用以下内容来查找度数符号和数字,但是如果它们完全出现在单元格中,它就会返回值,如果它们彼此相邻,则不一定。 So if I have data in the cell that says "Qty 90 of 45° elbows" and "Qty 45 of 90° elbows" it is causing issues.因此,如果我在单元格中有数据显示“45° 弯头的数量为 90”和“90° 的弯头数量为 45”,则会导致问题。

For Each cell In Range("A1:A5000")
If InStr(cell.Value, ChrW(176)) > 0 And cell Like "*45*" Then
    cell.Offset(0,5).Value = "45 Degree"
End If
Next cell

I figure I can do a work around and try to extract info from the cell, enter it into another one, and then search on that.我想我可以做一个解决方法并尝试从单元格中提取信息,将其输入到另一个单元格中,然后对其进行搜索。 But that's a pain.但这是一种痛苦。 Any ideas?有任何想法吗?

The Instr and Like operator are not mutually excluding which means you are getting "false positives". InstrLike运算符不相互排斥,这意味着您得到“误报”。 Why not just a single Like statement:为什么不只是一个Like语句:

Sub Test()

Dim arr As Variant: arr = Array("Qty 90 of 45° elbows", "Qty 45 of 90° elbows", "Qty 90 of 145° elbows")

'Using Like expressions:
For Each el In arr
    Debug.Print el Like "*45°*"
Next

'Using Regular expressions:
With CreateObject("vbscript.regexp")
    .Pattern = "(?:^|\D)45°(?:$|\D)"
    For Each el In arr
        Debug.Print .Test(el)
    Next
End With

End Sub

I'm not sure about your data and posibilities of degrees past 99. If possible you run the risk of false positives even with Like .我不确定您的数据和超过 99 度的可能性。如果可能的话,即使使用Like ,您也会面临误报的风险。 Therefore I included an alternative in the code above to use a regular expression instead.因此,我在上面的代码中包含了一个替代方法来使用正则表达式。


Extra: This is an assumption from my end, but it looks like you are trying to find the degrees (not just '45') and do some calculations or something alike?额外:这是我的一个假设,但看起来你正在尝试找到学位(不仅仅是“45”)并进行一些计算或类似的事情? If so, you could alter the pattern a little too:如果是这样,您也可以稍微改变模式:

Sub Test()

Dim arr As Variant: arr = Array("Qty 90 of 45° elbows", "Qty 45 of 90° elbows", "Qty 90 of 145° elbows")

With CreateObject("vbscript.regexp")
    .Global = True
    .Pattern = "^.*?(\d+)°.*$"
    For Each el In arr
        Debug.Print Val(.Replace(el, "$1"))
    Next
End With

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM