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