Excel VBA排除字

时间:2017-11-01 02:30:05

标签: excel excel-vba excel-formula vba

我有一些排除词,分别是:Limited,Corporation,Incorporation,Inc,Ltd和Co,分别在A2到A6单元格中。

在B栏中,它将分别为:ABC Limited,XYZ Holdings Corporation Limited和Tesco Bee Co Ltd的输入值,分别位于B2至B4单元格中。

在C栏中,它将显示B的结果,但不包括A栏中的任何或所有单词。它应分别显示ABC,XYZ Holdings和Tesco Bee的结果。

是否有任何公式或宏可以解决此问题?

我附上了一个链接到我试图说明的样本。

Screenshot here

我试过这段代码:

Sub test()
    Dim OriginalText As String
    Dim CorrectedText As String 
    OriginalText = Range("C4").Value 
    CorrectedText = Replace(OriginalText, "Limited", "") 
    Range("C4").Offset(, 1).Value = CorrectedText 
End Sub

但是,我不知道如何在其中加入所有排除词,目前我设法排除"有限"仅

1 个答案:

答案 0 :(得分:0)

把你的代码放到一个循环中:

Sub test()
    Dim Exclusions As Variant
    Dim CorrectedText As String 
    Dim r As Long
    Dim i As Long
    'Get all the "exclusions" from column A
    Exclusions = Range("A2", Range("A" & Rows.Count).End(xlUp)).Value
    'Loop through all the cells in column C
    For r = 2 To Cells(Rows.Count, "C").End(xlUp).Row
        'Start with the current value
        CorrectedText = Cells(r, "C").Value 
        'Remove, one word at a time, any words that are excluded
        For i = LBound(Exclusions, 1) To UBound(Exclusions, 1)
            CorrectedText = Replace(CorrectedText, Exclusions(i, 1), "") 
        Next
        'Put whatever is left in column D
        Cells(r, "D").Value = CorrectedText 
    Next
End Sub