VBA从单独的列表中替换多个字符串

时间:2014-08-01 06:22:15

标签: vba excel-vba excel

我需要替换STRINGS但到目前为止我只设法替换了单词。代码将通过Description列,并且应该替换列表中的每个序列。 我们的想法是使用缩写( new values )而不是完整的单词(旧值)。

每次有相邻(无空格)字,字符等时,代码都会失败。怎么了?谢谢!!!

Sub ReplaceWords_BUT_Need_ToReplaceStrings()

    Application.ScreenUpdating = False

    'This macro works with separated words only. Eliminate hyphens etc before applying this macro.

    Dim r As Range, A As Range
    Dim s1 As Worksheet, s2 As Worksheet, LastRow As Integer, v As String, j As Integer,      
    oldv As String, newv As String

    LastRow = Cells(Rows.count, "A").End(xlUp).row

    Set s1 = Sheets("JE_data")
    Set s2 = Sheets("ListToReplace")
    Set A = s1.Range("J:J").Cells.SpecialCells(xlCellTypeConstants)
    For Each r In A
        v = r.Value

        For j = 2 To LastRow

            oldv = s2.Cells(j, 1).text
            newv = s2.Cells(j, 2).text

'替换功能,因为您使用它是区分大小写的。   “你确定你的所有发票单词都以大写字母开头吗?   '如果没有,那么请使用v = Replace(v,oldv,newv,1,-1,vbTextCompare)函数。行。

        v = Replace(v, oldv, newv, 1, -1, vbTextCompare)    
        'v = Replace(v, oldv, newv)

        Next j
        r.Value = Trim(v)

    Next r

    Application.ScreenUpdating = True

End Sub

示例:

ListToReplace

Left column (old)     Right column (new)
----------------------------------------
Invoice               inv 
Salary                sy 
Credit                cr 

JE_data

cr Note
cr note 
INV/2712/14RF/0229/14 
Invoice 1078 10 
TECHNOQ01SI 2014 03288

编者注:我不知道这个例子是否正确,因为它是在评论中写的)

Credit已替换为crInvoice预计将替换为inv,但不是

1 个答案:

答案 0 :(得分:2)

替换功能,因为您使用它是区分大小写的。您确定所有发票单词都以大写字母开头吗?如果没有,那么使用

v = Replace(v, oldv, newv, 1, -1, vbTextCompare)

功能改为。