gpt4 book ai didi

excel - VBA/如何过滤精确字符串上的数组?

转载 作者:行者123 更新时间:2023-12-04 21:30:35 24 4
gpt4 key购买 nike

正如我的标题一样,我试图根据另一个数组从 VBA 数组中过滤掉特定的字符串。

我的代码看起来像这样:

For Each item In exclusions_list
updated_list = Filter(updated_list, item, False, vbTextCompare)
Next item

我的问题是我只想排除完全匹配,我似乎找不到这样做的方法。

如果我在 excludes_list 中有“how”,我想从 updated_list 中排除“how”,而不是“however”。

如果以前有人问过这个问题,我深表歉意。我找不到明确的答案,我对 VBA 也不是很熟悉。

谢谢 !

最佳答案

Filter方法只查找子字符串。它没有办法识别整个单词。

一种方法是使用 Regular Expressions其中包括一个用于识别单词边界的标记。这仅在您考虑的子字符串不包含非 Word 字符时才有效。单词字符是 [A-Za-z0-9_] 集合中的字符。 (非英语语言有一些异常(exception))。

例如:

Option Explicit
Sub foo()
Dim arr
Dim arrRes
Dim V
Const sfilter As String = "gi"
Dim col As Collection

arr = Array("Filter", "by", "bynomore", "gi", "gif")

Dim re As Object, MC As Object, I As Long
Set col = New Collection
Set re = CreateObject("vbscript.regexp")
With re
.ignorecase = True
.Pattern = "\b" & sfilter & "\b"
For I = 0 To UBound(arr)
If .test(arr(I)) = False Then _
col.Add arr(I)
Next I
End With
ReDim arrRes(0 To col.Count - 1)
For I = 1 To col.Count
arrRes(I - 1) = col(I)
Next I
End Sub

结果数组 arrRes将包含 gif但不是 gi

关于excel - VBA/如何过滤精确字符串上的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53157325/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com