excel - 循环遍历拆分值单元格并替换

标签 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

最佳答案

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

我已经对代码进行了注释,因此您理解它应该没有问题。但是,如果您这样做,则只需回帖即可。

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

关于excel - 循环遍历拆分值单元格并替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30208601/

相关文章:

vba - MS Access复制表到另一个表VBA代码

javascript - 使用 JavaScript 迭代 JSON 数组中的对象

jquery 嵌套 .each

excel - 如何判断趋势线是上升还是下降

javascript - 下载使用 SheetJS/XLXS 在 Node 中创建的 excel 文件 [NodeJS] [React]

vba - 引用 UDF 中的特定单元格

vba - Excel VBA,for循环忽略隐藏行

ms-access - 从网站上的表格中抓取数据,而无需搜索标签

ios - 更新元组数组中的每个键

excel - 防止 Yii2 kartik 中的科学计数法数字导出为 excel 单元格格式