使用可能的通配符查找和替换的VBA代码?

时间:2017-08-18 19:31:46

标签: excel-vba vba excel

如何从字符串中找到并删除X,换句话说,用N1代替NX1,用N75代替NX2,用N7535代替NX7535,所有字符串都以N开头但不是N之后都有X,如果需要的话我需要删除那个X,下面我把疯狂的代码改编自excel录音,但它必须更容易实现:

   Sub Find_NX_Replace()



     Range("A1").Select
     Range(Selection, Selection.End(xlDown)).Select
     Selection.Replace What:="NX1", Replacement:="N1", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

    Selection.Replace What:="NX2", Replacement:="N2", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

     Selection.Replace What:="NX3", Replacement:="N3", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

 Selection.Replace What:="NX4", Replacement:="N4", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

     Selection.Replace What:="NX5", Replacement:="N5", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

    Selection.Replace What:="NX6", Replacement:="N6", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

     Selection.Replace What:="NX7", Replacement:="N7", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

    Selection.Replace What:="NX8", Replacement:="N8", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False


     Selection.Replace What:="NX9", Replacement:="N9", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False




   End Sub

示例:

enter image description here

1 个答案:

答案 0 :(得分:2)

执行数字循环:

Sub Find_NX_Replace()
    Dim i as Long
    For i = 1 To 9
        Selection.Replace What:="NX" & i, Replacement:="N" & i, LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
    Next i

End Sub