Excel 2013 here - 我试图将单元格D中的值与单元格C中的值进行匹配。让我脱掉头发的部分是,如果C列中存在单个单词,则应该是从D栏中删除。
例如
Column C Column D
Red Hairy Hats Hairy Cowpies
由于两个字段都包含单词Hairy
,因此应将其更新为“
Column C Column D
Red Hairy Hats Cowpies
我无法揭示如何在Excel VBA中对字符串比较进行通配符匹配。我有这种语法可以进行 Exact 匹配,但是我怎么能像上面的例子那样从字符串中做单个单词呢?
Dim i As Long
Dim resArry
dataArry = Cells(1).CurrentRegion
ReDim resArry(UBound(dataArry, 1) - 1, 1)
For i = 2 To UBound(dataArry, 1)
If InStr(1, dataArry(i, 3), dataArry(i, 4), vbBinaryCompare) Then
resArry(i - 2, 0) = ""
Else
resArry(i - 2, 0) = dataArry(i, 4)
End If
Next
Range("D2").Resize(UBound(resArry, 1)) = resArry
答案 0 :(得分:1)
带有变体数组的RegExp选项。
针对每个D字符串为每个C字符串创建一个模式,以便仅替换整个单词
\ B(红色|毛状|帽子)\ B'/ P>
等
Sub Interesting()
Dim rng1 As Range
Dim X, Y
Dim lngCnt As Long
Dim ObjRegex As Object
Set rng1 = Range([c1], Cells(Rows.Count, "c").End(xlUp))
X = rng1.Value2
Y = rng1.Offset(0, 1).Value2
Set ObjRegex = CreateObject("vbscript.regexp")
With ObjRegex
.Global = True
For lngCnt = 1 To UBound(X, 1)
.Pattern = "\b(" & Join(Split(X(lngCnt, 1), Chr(32)), "|") & ")\b"
Y(lngCnt, 1) = .Replace(Y(lngCnt, 1), vbNullString)
Next
End With
rng1.Offset(0, 1).Value2 = Y
End Sub
答案 1 :(得分:0)
这不是一个完整的答案,因为我对VBA有点生疏,但不是使用instr
来寻找匹配,你可能会更成功地将两个字符串分成数组。
这个过程是这样的:
答案 2 :(得分:0)
Private Sub Test()
Dim C As String, D As String
C = "Red Hairy Hats"
D = "hairy cowpies"
Debug.Print RemoveMatches(C, D)
End Sub
Private Function RemoveMatches(C As String, D As String) As String
Dim Sp() As String
Dim i As Integer
Sp = Split(C)
For i = 0 To UBound(Sp)
If InStr(1, D, Sp(i), vbTextCompare) Then
D = Trim(Replace(D, Sp(i), "", Compare:=vbTextCompare))
End If
Next i
RemoveMatches = D
End Function