【问题标题】:Finding a string in comma seperated column with excel vba使用excel vba在逗号分隔的列中查找字符串
【发布时间】:2020-01-21 19:40:55
【问题描述】:

使用 Excel VBA,我必须在选定列中搜索特定的零件编号。该列具有以逗号分隔的部件号。 列中的数据是这样的

A 栏

ab,ca,ade,ar

ad,aw,dr ...

当我在该列上为 "ad" 执行 Selection.Find 时,它返回具有 'ade' 的第一行 无法查找整个单元格,因为该列的任何单元格中有超过 1 个部件号 这是我用来完成该任务的代码。

Set Cell = Selection.Find(What:=:"ad", after:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)  ' This is BUG that needs correction for xlPart

If Cell Is Nothing Then
        ….
End If

解决此问题的最佳和有效方法是什么

提前感谢您的帮助...:)

【问题讨论】:

  • 将该列读取为:第一行 - ab,ac,ade ;第二行 ac,ar,fc, 第三行:;;;;;;
  • ad,怎么样?
  • 部件号可以在该单元格中的任何位置 - 它可以是不以逗号结尾的 ar,ae,ade
  • 在这种情况下,您可以使用RegExp 而不是Excel 的FIND 方法,其中模式可以是\bad\b

标签: excel


【解决方案1】:

您可以使用基于RegExp 的函数,如下所示

Public Function blCheckString(InputRange As Range, strChkString) As Boolean
Dim objRgEx As Object
Set objRgEx = CreateObject("VBScript.RegExp")
With objRgEx
    .Pattern = "\b" & strChkString & "\b"
    If .Test(InputRange.Value) Then
        blCheckString = True
    Else
        blCheckString = False
    End If
End With
Set objRgEx = Nothing
End Function

然后可以在下面的代码中使用它。

Sub Test()
If blCheckString(Selection, "ad") Then
    MsgBox "Success"
Else
    MsgBox "No Success"
End If
End Sub

【讨论】:

  • @MaheshSubramaniam,然后请将其标记为答案并投票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-19
  • 1970-01-01
  • 2014-08-04
  • 1970-01-01
  • 2020-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多