遍历拆分值单元格并替换

Loop through split value cells and replace

我在 Excel 中创建了一个宏。在 A 列中,值以分号分隔。

A 列中的拆分值替换 B 列中的拆分值存在循环。

循环拆分值不起作用。

Sub ReplaceAttachments3()
Dim cl As Range
Dim cell As Variant
Dim i As Long
Dim txt As String
For Each cl In Range("$B:$B" & Range("$B65536").End(xlUp).Row)
    txt = Cells(cl.Row, 1)
    cell = split(txt, ";")
    For i = 0 To UBound(cell)
        Cells(cl.Row, 2).replace What:=txt,   Replacement:="",LookAt:=xlPart, SearchOrder:= _
            xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
        Application.Goto Reference:="ReplaceAttachments"
    Next i
Next
End Sub

这是你正在尝试的吗?请注意,您不需要 select 完整的列。只需找到最后一行并仅使用该范围:)

我已经对代码进行了注释,因此您理解它应该没有问题。但如果你这样做了,那么只需 post 返回。

Sub Sample()
    Dim ws As Worksheet
    Dim aCell As Range, rng As Range
    Dim Lrow As Long, i As Long
    Dim MyAr

    '~~> Change this to the relevant worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        '~~> Find the last row in Col A
        Lrow = .Range("A" & .Rows.Count).End(xlUp).Row

        '~~> Set your range
        Set rng = .Range("A1:A" & Lrow)

        '~~> Loop trhough your range
        For Each aCell In rng
            '~~> Skip the row if value in cell A is blank
            If Len(Trim(aCell.Value)) <> 0 Then
                '~~> Check if the cell has ";"
                '~~> If it has ";" then split and replace else
                '~~> Replace without splitting
                If InStr(1, aCell.Value, ";") Then
                    MyAr = Split(aCell.Value, ";")

                    For i = LBound(MyAr) To UBound(MyAr)
                        aCell.Offset(, 1).Value = Replace(aCell.Offset(, 1).Value, Trim(MyAr(i)), "")
                    Next i
                Else
                    aCell.Offset(, 1).Value = Replace(aCell.Offset(, 1).Value, Trim(aCell.Value), "")
                End If
            End If
        Next
    End With
End Sub

截图: