我需要vBA coe来用另一个字符串替换Excel工作表中的字符串列表

时间:2017-11-13 00:45:25

标签: excel vba

我在VBA中需要这样的代码

Sub ReplaceCourseCode()

    if(string in a cell= "john")
             replace string in a cell with "ThunderJohn"
    elseif(string in a cell ="David)
              replace string in a cell with "ThunderDavie"
    else move to next cell
End Sub

2 个答案:

答案 0 :(得分:0)

以下两个程序中的任何一个都可以达到你想要的效果。第二个将更快地工作,因为它不像第一个那样经常引用工作表,但它也使用不同的系统来设置比较。您可以将方法和系统混合在一起,以最适合您希望完成工作的环境。

Option Explicit

Sub ChangeName_1()

    Const Target As String = "B2:B100"          ' change as required
    Dim Cell As Range

    Application.ScreenUpdating = False
    For Each Cell In ActiveSheet.Range(Target)
        With Cell
            If StrComp(Trim(.Value), "john", vbTextCompare) = 0 Then
                .Value = "ThunderJohn"
            ElseIf StrComp(Trim(.Value), "David", vbTextCompare) = 0 Then
                .Value = "ThunderDavid"
            End If
        End With
    Next Cell
    Application.ScreenUpdating = True
End Sub

Sub ChangeName_2()

    Const Target As String = "B2:B100"          ' change as required
    Dim Cell As Range
    Dim Txt As String

    Application.ScreenUpdating = False
    For Each Cell In ActiveSheet.Range(Target)
        With Cell
            Txt = Trim(LCase(.Value))
            If Len(Txt) Then
                If InStr(1, "john,david", Txt, vbTextCompare) Then
                    .Value = "Thunder" & UCase(Left(Txt, 1)) & Mid(Txt, 2)
                End If
            End If
        End With
    Next Cell
    Application.ScreenUpdating = True
End Sub

答案 1 :(得分:0)

与VBA中的大多数任务一样,有许多不同的方法可以产生相同的结果。这是一对......

这个循环遍历您指定的单元格,或者您可以用Range("A1:B3")替换ActiveSheet.UsedRange以遍历工作表上的所有“已使用”单元格:

Sub ReplaceCourseCode()
    Dim c As Range
    For Each c In Range("A1:B3") 'specify the search range (on the active worksheet)
        If c = "john" Then
            c = "ThunderJohn"
        ElseIf c = "David" Then
            c = "ThunderDavie"
        End If
    Next c
End Sub    

或者,如果您只是想要自动化简单的搜索和替换(如 CTRL + H )整个工作表,每次搜索只需要一行代码:

Sub FindReplace()
    Cells.Replace What:="john", Replacement:="ThunderJohn", MatchCase:=False
    Cells.Replace What:="David", Replacement:="ThunderDavie", MatchCase:=False
End Sub

进一步阅读: