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

删除回忆录丶 提交于 2019-12-12 06:10:35

问题


This is an extension of a previously asked question that was amazingly answered and made me think of how else I can simplify my sloppy code.

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

回答1:


Take the left of the string, the number of chars is equal to the total length minus 4

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



回答2:


Or directly via two array IF tests

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


来源:https://stackoverflow.com/questions/28686052/excel-macro-if-the-final-characters-of-a-cell-is-something-then-cut-them-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!