1

是否可以简化以下代码?有什么办法可以缩短这个:

    ' 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 和编码的新手,所以请多多包涵:)

4

3 回答 3

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)
于 2013-10-16T15:01:32.567 回答
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
于 2013-10-16T15:04:04.250 回答
1

通常,您要避免使用SelectandSelection语句。他们有自己的位置,但很少见。你最好跳过这一步,而是做你想做的事。

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
于 2013-10-16T15:05:01.297 回答