简体   繁体   English

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

[英]Shortening words based on database in Excel VBA

I am currently trying to replace words in a cell with shorter versions in mass. 我目前正在尝试用更短的版本替换单元格中的单词。 I have a dictionary of words to make shorter and will have a column of cells that need to have one or more of the words shortened. 我有一个要缩短的单词字典,并且有一列需要将一个或多个单词缩短的单元格。

I am very new to VBA and I'm not sure how I would go about this. 我对VBA非常陌生,我不确定该如何处理。 I tried searching and found some that would be changing text in a word doc but nothing from Excel to excel, at least with my search terms. 我尝试搜索,发现其中一些会更改Word文档中的文本,但至少从我的搜索字词来看,从Excel到excel没有任何改变。

I have added a picture here of the Idea, the Text to be shortened is in column A, the words that can be shortened are in column C and the shortened versions are in column D. 我在此处添加了该创意的图片,要缩短的文本在A列中,可以缩写的单词在C列中,而缩短的版本在D列中。

Sample 样品

You can use this UDF. 您可以使用此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

Place this code in your regular module. 将此代码放在常规模块中。 then write this formula =SubstituteMultiple(A2,$C$2:$C$11,$D$2:$D$11) in cell B2 and drag it to the bottom. 然后在单元格B2编写此公式=SubstituteMultiple(A2,$C$2:$C$11,$D$2:$D$11)并将其拖到底部。

在此处输入图片说明

Here's a full sub version if that works better for you 这是完整的子版本,如果更适合您

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

Perhaps simple replace in VBA would do it, 也许用VBA进行简单替换就可以做到,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM