替换上一个出现的字符

时间:2016-09-08 14:25:40

标签: excel-vba vba excel

我有一个电子表格,其中包含许多文件路径。我使用以下公式来替换最后一次出现的" \"在列的每个单元格中。如何将其更改为宏,以便我不必粘贴并向下拖动每列。

=SUBSTITUTE(K2,"\","?",LEN(K2)-LEN(SUBSTITUTE(K2,"\","")))

我尝试录制一个宏,但只能在一个单元格上运行,并且只有当活动单元格位于O列时

Sub Macro4()
ActiveCell.FormulaR1C1 = _
    "=SUBSTITUTE(RC[-4],""\"",""?"",LEN(RC[-4])-LEN(SUBSTITUTE(RC[-4],""\"","""")))"
Range("O2").Select
End Sub

无论活动单元是什么,我都需要将这个值从O2开始,从O2开始,每个非空K从K2开始。

1 个答案:

答案 0 :(得分:1)

这是另一种方法:

Sub LastSlash()
    Dim N As Long, i As Long, rng As Range, r As Range
    Dim rc As Long, L As Long, j As Long

    rc = Rows.Count
    Set rng = Intersect(ActiveSheet.UsedRange, Range("K2:K" & rc))
    N = Cells(rc, "K").End(xlUp).Row

    For Each r In rng
        s = r.Value
        L = Len(s)
        If InStr(1, s, "\") > 0 Then
            For j = L To 1 Step -1
                If Mid(s, j, 1) = "\" Then
                    Mid(s, j, 1) = "?"
                    Exit For
                End If
            Next j
        End If
        r.Offset(0, 4).Value = s
    Next r
End Sub

enter image description here