2014-07-08 70 views
0

我想將具有公式的最後一行從工作表複製到下一行,然後將剛刪除的行復製出來。例如,我有列A到W的公式,我當前的最後一行是10,我想複製第10行到第11行,然後將第10行的值複製出來。嘗試使vba代碼自動執行過程。任何幫助讚賞。將數據的最後一行復制到下一行

+1

能否請您先發布自己的代碼,並告訴我們在哪兒它拋出一個錯誤? – hnk

+0

你有什麼嘗試?詢問不包括任何現有企圖的代碼的問題往往會在這裏很快關閉。 –

回答

0

這應該讓你在正確的方向開始:

Sub appendToEnd() 

    Dim myLastCell As Range 
    Set myLastCell = LastCell(Worksheets("Sheet1").Range("A:W")) 
    Dim lastCellCoords As String: lastCellCoords = "A" & myLastCell.Row & ":W" & myLastCell.Row 

    Dim firstEmptyRow As Integer: firstEmptyRow = myLastCell.Row + 1 
    Dim firstEmptyCoords As String: firstEmptyCoords = "A" & firstEmptyRow & ":W" & firstEmptyRow 

    If Not myLastCell Is Nothing Then 
     ' Now Copy the range: 
     Worksheets("Sheet1").Range(lastCellCoords).Copy 
     ' And paste to first empty row 
     Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues 
     Application.CutCopyMode = False 
    Else 
     MsgBox ("There is no data in specified range") 
    End If 

End Sub 

Function LastCell(r As Range) As Range 

' 
' Note "&" denotes a long value; "%" denotes an integer value 

    Dim LastRow&, lastCol% 

    On Error Resume Next 

    With r 

    ' Find the last real row 

    LastRow& = .Cells.Find(What:="*", _ 
     SearchDirection:=xlPrevious, _ 
     SearchOrder:=xlByRows).Row 

    ' Find the last real column 

    lastCol% = .Cells.Find(What:="*", _ 
     SearchDirection:=xlPrevious, _ 
     SearchOrder:=xlByColumns).Column 

    End With 

' Finally, initialize a Range object variable for 
' the last populated row. 

    Set LastCell = r.Cells(LastRow&, lastCol%) 


End Function 
+0

這很好。我不得不稍微調整一下,因爲它將值粘貼到最後一行,並在前一行保留公式,但您的回答非常有幫助。謝謝。 – user3818371

+0

非常歡迎! –

相關問題