在Excel VBA中缩短基于数据库的单词

我目前正在尝试用质量较短的版本replace单元格中的单词。 我有一个单词词典缩短,将有一列单元格,需要有一个或更多的单词缩短。

我对VBA很新,我不确定我会怎么做。 我尝试search,发现一些将改变文字文件中的文本,但没有什么从Excel优秀,至less我的search条件。

我在这里添加了一个想法的图片,要缩短的文本是在A栏中,可以缩短的文字在C列,缩短的文本在D列。

样品

这是一个完整的子版本,如果这对你更好

Sub ReplaceViaList() Dim ws As Worksheet Dim repRng As Range Dim x As Long, lastRow As Long Dim repCol As Long, oldCol As Long, newCol As Long Dim oldStr As String, newStr As String 'screenupdating/calc Application.Calculation = xlCalculationManual Application.ScreenUpdating = False 'define worksheet Set ws = ActiveSheet 'define columns to work with repCol = 1 'col A oldCol = 3 'col C newCol = 4 'col D 'find last row of replacement terms lastRow = ws.Cells(ws.Rows.Count, repCol).End(xlUp).Row 'set range of items to be replaced Set repRng = ws.Range( _ ws.Cells(2, repCol), _ ws.Cells(lastRow, repCol) _ ) 'loop through cells in replacement terms For x = 2 To ws.Cells(ws.Rows.Count, oldCol).End(xlUp).Row 'define replacement terms oldStr = ws.Cells(x, oldCol).Value newStr = ws.Cells(x, newCol).Value 'replace repRng.Replace What:=oldStr, Replacement:=newStr Next x 'screenupdating/calc Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub 

你可以使用这个UDF。

 Function SubstituteMultiple(text As String, old_text As Range, new_text As Range) Dim i As Single For i = 1 To old_text.Cells.Count Result = Replace(LCase(text), LCase(old_text.Cells(i)), LCase(new_text.Cells(i))) text = Result Next i SubstituteMultiple = Result End Function 

将此代码放在常规模块中。 然后在B2单元格中写下这个公式=SubstituteMultiple(A2,$C$2:$C$11,$D$2:$D$11) ,并将其拖动到底部。

在这里输入图像说明

也许在VBA中简单的replace就可以了,

 Sub test() Dim searchval As Variant Dim replaceval As Variant searchval = Range("C1:C10") replaceval = Range("D1:D10") For i = 1 To 10 Columns("A:A").Replace What:=searchval(i, 1), Replacement:=replaceval(i, 1), LookAt:=xlPart Next i End Sub