句子中的替代词

时间:2018-05-16 00:57:08

标签: excel vba excel-vba replace substitution

如果单元格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  
    

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

此功能可在工作表或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

实施例

要获得与您的示例匹配的输出:

img

...或者如果您不想像这样“硬编码”源代码值,您可以改为引用单元格,例如:

img

无论哪种方式,源数据都必须来自“某处”,因为工作表单元格不能同时包含值和公式。或者,可以将函数转换为子例程,然后在需要时执行。