Excel宏:如果单元格的最终字符是“某事物”,则将它们剪切并粘贴到其他位置

时间:2015-02-24 00:12:47

标签: excel excel-vba if-statement paste vba

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

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

或直接通过两个阵列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