2013-10-16 104 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