【问题标题】:substitute words in sentence替换句子中的单词
【发布时间】:2018-05-16 00:57:08
【问题描述】:
如果单元格A1 包含一个值,我想知道如何从句子(A2)中消除它。
示例:
-
未经修改(原创):
A1 = (null)
A2 = 1,2,3,4,5,6,7,8,9
-
修改后:
if A1 = 2,5,8
A2 = 1,3,4,6,7,9
【问题讨论】:
标签:
vba
excel
replace
substitution
【解决方案1】:
在 A1 和 A2 中输入值后,运行这个简短的宏:
Sub removewords()
Dim veto As Boolean, temp As String
ary1 = Split([a1], ",")
ary2 = Split([a2], ",")
For Each a In ary2
veto = False
For Each b In ary1
If a = b Then veto = True
Next b
If Not veto Then temp = temp & "," & a
Next a
[a2] = Mid(temp, 2)
End Sub
【解决方案2】:
这个函数可以在工作表或VBA中使用:
Function removeWords(words, wordsToExclude) As String
Dim w: For Each w In Split(words, ",")
If InStr(wordsToExclude, w) = 0 Then removeWords = removeWords & "," & w
Next: removeWords = Mid(removeWords, 2)
End Function
示例:
要获得与您的示例匹配的输出:
...或者如果您不想像这样“硬编码”源值,您可以引用一个单元格,例如:
无论哪种方式,源数据都必须来自“某处”,因为工作表单元格不能同时包含值和公式。或者,可以将函数转换为子程序,然后在需要时执行。