Excel vba最后查找并替换

时间:2017-04-17 03:35:08

标签: excel vba excel-vba replace

我必须在最后更换变体。我们可以这样做,如果有的话,请任何人帮忙吗?

代码:

Worksheets("Part_Number").Columns("F").Replace What:="-G", Replacement:=" ", SearchOrder:=xlByColumns, MatchCase:=True

输入:

WA-2001-G 
WA-GSK024

预期产出:

WA-2001 
WA-GSK024

3 个答案:

答案 0 :(得分:2)

What:="-G"上,您需要添加"space -G space"

假设您尝试做什么

示例

Option Explicit
Public Sub Example()
    With ThisWorkbook.Sheets("Part_Number").Range("F:F")
        .Replace " -G ", " ", xlPart
    End With
End Sub

示例
WA-2001 -G WA-GSK024
到此 WA-2001 WA-GSK024

编辑如果没有空格,请使用此

Option Explicit
Public Sub Example()
    Dim rng As Range

    With ThisWorkbook.Sheets("Part_Number")
        For Each rng In .Range("F1", Range("F99").End(xlUp))
            If Right(rng.Value, 2) = "-G" Then
                 Debug.Print rng.Value ' Immediate Window
                rng.Value = Mid(rng.Value, 1, Len(rng.Value) - 2)
                 Debug.Print rng.Value ' Immediate Window
            End If
        Next
    End With
End Sub

答案 1 :(得分:2)

这样做的一种方法是循环Column F并检查每个单元格中-G的最后两个字符,如果存在则删除。请参阅以下代码:

Public Sub Demo()
    Dim lastRow, i As Long
    Dim myString As String
    Dim c As Range
    'get the last row with data in Column `F`
    lastRow = Cells(Rows.Count, "F").End(xlUp).Row

    For Each c In ThisWorkbook.Sheets("Sheet1").Range("F1:F" & lastRow)
        If Len(c.Value) <> 0 Then
            If Right(c.Value, 2) = "-G" Then c.Value = Left(c.Value, Len(c.Value) - 2)
        End If
    Next c
End Sub

如果有什么不清楚,请告诉我。

答案 2 :(得分:1)

或者您可以尝试这样的事情......

Sub ReplaceStrings()
    Dim ws As Worksheet
    Dim lr As Long
    Set ws = Sheets("Part_Number")
    ws.Activate
    lr = Cells(Rows.Count, "F").End(xlUp).Row
    Range("F2:F" & lr).Value = Evaluate("If(Right(Trim(F2:F" & lr & "),2)=""-G"",Left(Trim(F2:F" & lr & "),Len(Trim(F2:F" & lr & "))-2),F2:F" & lr & ")")
End Sub