在excel 2007中的列中查找并替换多个单词

时间:2014-07-07 04:57:43

标签: excel vba

Sub xLator2()
Dim s1 As Worksheet, s2 As Worksheet
Dim N As Long, i As Long
Dim from(), too()
Set s1 = Sheets("Sheet1") '   contains the data
Set s2 = Sheets("Sheet2") '   contains the translation table

s2.Activate

N = Cells(Rows.Count, 1).End(xlUp).Row
ReDim from(1 To N)
ReDim too(1 To N)
For i = 1 To N
    from(i) = Cells(i, 1).Value
    too(i) = Cells(i, 2).Value
Next i

s1.Activate

For i = LBound(from) To UBound(from)
    Cells.Replace What:=from(i), Replacement:=too(i)
Next i
End Sub

我正在使用上面的代码来查找和替换多个单词(在"列A表1和#34;单词在#34; B栏表2和#34;中)在下面提到的表格中:

https://docs.google.com/spreadsheets/d/15TRLccDr_EAR8s78u-WGSkGpAecBf42_lhRkjCev_WE/edit?usp=sharing

然而,当我在另一张表格(如下所述)中将其应用于其他数据时,代码失败,即我在sheet1中得到扭曲的单词:

https://docs.google.com/spreadsheets/d/14ba9pQDjMPWJd4YFpGffhtVcHxml0LdUUVQ0prrOEUY/edit?usp=sharing

请帮帮我,以便我可以替换" A栏表1和#34;单词" B栏表2"
注意:以上链接已经提供了谷歌电子表格,但我在Excel 2007表格中遇到问题 我请求你通过提供完整的修改代码来帮助我,因为我不擅长VBA

1 个答案:

答案 0 :(得分:0)

在Excel中我发现了一些问题 Fisrt 它始终指向具有前缀

的单元格
ActiveSheet.Cells ...

<强>第二即可。出现奇怪的单词是因为查找/替换单词的替换部分。如果您不想使用:

ActiveSheet.Cells.Replace What:=from(i), Replacement:=too(i), LookAt:=xlWhole

<强>第三即可。所有Sheet1上的查找/替换工作。如果您只想要列&#34; A&#34;:

ActiveSheet.Range("A:A").Select
For i = LBound(from) To UBound(from)
    Selection.Replace What:=from(i), Replacement:=too(i), LookAt:=xlWhole
Next i