可以简化以下代码吗?有没有办法缩短它:
' Paste last value
Range(Cells(LastRowP + 1, 10), Cells(LastRowP + 1, 10)).Select
Selection.Cut
Range(Cells(LastRowP + 1, 9), Cells(LastRowP + 1, 9)).Select
ActiveSheet.Paste
Range(Cells(LastRowP + 2, 10), Cells(LastRowP + 2, 10)).Select
Selection.Cut
Range(Cells(LastRowP + 2, 9), Cells(LastRowP + 2, 9)).Select
ActiveSheet.Paste
Range(Cells(LastRowP + 3, 10), Cells(LastRowP + 3, 10)).Select
Selection.Cut
Range(Cells(LastRowP + 3, 9), Cells(LastRowP + 3, 9)).Select
ActiveSheet.Paste
这一直持续到+20。我是VBA和编码的新手,所以请耐心等待我:)
答案 0 :(得分:5)
Range(Cells(LastRowP + 1, 10), Cells(LastRowP + 20, 10)).Cut _
Cells(LastRowP + 1, 9)
或
Cells(LastRowP + 1, 10).Resize(20,1).Cut Cells(LastRowP + 1, 9)
答案 1 :(得分:2)
For i = 1 To 20
Range(Cells(LastRowP + i, 10), Cells(LastRowP + i, 10)).Cut
Range(Cells(LastRowP + i, 9), Cells(LastRowP + i, 9)).Select
ActiveSheet.Paste
Next
答案 2 :(得分:1)
通常,您希望避免使用Select
和Selection
语句。他们有自己的位置但很少见。你最好不要跳过那一步,而是快速做你想做的事。
Dim yourSheet As Worksheet
Dim offset As Long, maxOffset As Long, lastRowP As Long
Dim source As Range, destination As Range
'you always want to be explicit about what sheet you are using
'when you are not explicit unexplected things can happen
Set yourSheet = Sheets("yourSheetName")
maxOffset = 20 ' or however many times you need to do this loop
lastRowP = 10 ' or however you are setting this value
With yourSheet 'starting any statment with a . inside the With will reference this object
For offset = 0 To maxOffset
Set source = .Range(.Cells(lastRowP + offset, 10), .Cells(lastRowP + offset, 10))
Set destination = .Range(.Cells(lastRowP + offset, 9), .Cells(lastRowP + offset, 9))
source.Cut destination
Next offset
End With