用不同的字符替换第一次和第二次出现

时间:2017-06-02 10:19:33

标签: excel vba excel-vba excel-formula

我有一个可以批量替换的vba代码。

我想(通过VBA或公式)将“%”的第一次出现替换为“(”,并将“%”的第二次出现替换为“)”。

我的数据在B栏。

这是我的VBA代码:

Sub Multi_FindReplace()

Dim sht As Worksheet
Dim fndList As Variant
Dim rplcList As Variant
Dim x As Long

fndList = Array("_", "VOSTFR.mp4", "VF.mp4")
rplcList = Array(" ", "VOSTFR", "VF")

'Loop through each item in Array lists
  For x = LBound(fndList) To UBound(fndList)
    'Loop through each worksheet in ActiveWorkbook
      For Each sht In ActiveWorkbook.Worksheets
        sht.Cells.Replace What:=fndList(x), Replacement:=rplcList(x), _
          LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
          SearchFormat:=False, ReplaceFormat:=False
      Next sht

  Next x

End Sub

谢谢! :)

1 个答案:

答案 0 :(得分:3)

Cell C1中输入以下任一公式:

=SUBSTITUTE(SUBSTITUTE(B1,"%","(",1),"%",")",1)

=REPLACE(REPLACE(B1,FIND("%",B1),1,"("),FIND("%",REPLACE(B1,FIND("%",B1),1,"(")),1,")")

根据需要拖动/复制。见图片以供参考。

enter image description here

如果少于两个%,公式将抛出错误。因此,为避免错误,请将公式中的IFERROR用作

=IFERROR(REPLACE(REPLACE(B1,FIND("%",B1),1,"("),FIND("%",REPLACE(B1,FIND("%",B1),1,"(")),1,")"),"")