2013-10-16 101 views
1

是否可以簡化下面的代碼?有什麼辦法可以縮短這個時間:Excel VBA:簡化長代碼

' 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和編碼,所以請多多包涵:)

回答

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 
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

一般要避免使用SelectSelection語句。他們有自己的位置,但很少見。你跳過這一步要好得多,而只是做你想做的事情。

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