Excel 宏:如果单元格的最后一个字符是 "something" 那么,将它们剪切并粘贴到其他地方

Excel Macro: If the final characters of a cell is "something" then, cut them and paste them elsewhere

这是对之前提出的一个问题的扩展,这个问题得到了惊人的回答,让我想到了如何简化我草率的代码。

Dim i As Long, l As Long
l = Cells(Rows.Count, 4).End(xlUp).Row
For i = l To 1 Step -1
  If Right(Cells(i, 4).Value, 4) = " XX " Then 

   'do some stuff to cut and paste that ending to ColumnE'
    Cells(i, 5) = " XX "

   'i'm trying to do something like this to clear the final 4 characters.
    Right(Cells(i, 4).Value, 4).ClearContents

  End If
Next i

取字符串左边,字符数等于总长度减4

Cells(i,4).Formula = Left(Cells(i, 4).Value, len(Cells(i, 4).Value)-4)

或者直接通过两个数组IF测试

Sub Recut()
Dim lngCnt As Long
lngCnt = Cells(Rows.Count, "D").End(xlUp).Row
[e1].Resize(lngCnt, 1) = Application.Evaluate("=IF(RIGHT(D1:D" & lngCnt & ",4)="" XX "","" XX "","""")")
[d1].Resize(lngCnt, 1) = Application.Evaluate("=IF(RIGHT(D1:D" & lngCnt & ",4)="" XX "",LEFT(D1:D1000,LEN(D1:D" & lngCnt & ")-4),D1:D" & lngCnt & ")")
End Sub