循环拆分值单元格并替换

时间:2015-05-13 07:41:43

标签: excel vba foreach split str-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$1:$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

1 个答案:

答案 0 :(得分:1)

这是你在尝试什么?请注意,您无需选择完整列。只需查找最后一行并仅使用该范围:)

我已对代码进行了评论,因此您不应该对其进行理解。但如果你这样做,那么只需回发。

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

<强>截图:

enter image description here