2017-06-23 69 views
2

我的目標:
複製每個當前區域的最後一行並將它們粘貼到A26區域。
所以A26將成爲新地區的第一個單元。
也切換單元格內容。
請注意,單元格A中的內容=新範圍內的單元格C,其中B-> E,C-> B,D-> D,E-> A。
預期結果如下圖所示。VBA:複製和粘貼當前區域的最後一行

問題在當前代碼:
我不知道如何複製所有單元格並將其粘貼到各自的列。
而不是僅突出顯示最後一行,
某些當前區域突出顯示最後2行。
也是當前代碼,只複製工作表中最後一行,因爲它正在循環中被覆蓋?

expected results

Dim ws As Worksheets 
Dim rng As Range 
Dim r As Long 
Dim wb As Workbook 

Set wb = ThisWorkbook 
For Each ws In wb.Worksheets   
    If ws.Name = "Master" Then 
    For Each rng In ws.UsedRange.SpecialCells(xlCellTypeConstants, 3).Areas 
      r = rng.Cells(rng.Rows.Count, 1).Row 'last row 
     Set rng = ws.Range(Cells(r, "A"), Cells(r, "J")) 'range = last row cells from col A-J 
     rng.Interior.ColorIndex = 3 'highlight that range 
     rng.Copy 
     ws.Range("A26").PasteSpecial xlPasteValues 'paste them all to same sheet A26 
    Next rng 
    End If 
Next ws 
End Sub 

我還是新的VBA。任何人都能給我一些啓示嗎?

+0

你可以給你的代碼添加更多的上下文嗎?變量聲明代碼將有助於 –

+0

@MarkFitzgerald,我在代碼中添加了變量聲明。 – Santa

+0

我需要看到整個Sub,因爲還有更多的事情 - 'ws'(可能)被設置成循環,並且必須有一些代碼在複製/粘貼後重新排列列。看一看[mcve]的內容。 –

回答

0
rng.Copy 
ws.Range("A26").PasteSpecial xlPasteValues 'paste them all to same sheet A26 

您的代碼始終覆蓋在同一行。爲了避免這種情況可以改變上述表述成

Dim pasteRow As Long 
pasteRow = ws.Cells(ws.Rows.count, 1).End(xlUp).row + 1 
If pasteRow < 26 Then pasteRow = 26 
ws.Cells(pasteRow, "A").Resize(,rng.Columns.Count).Value = rng.Value 

B-> E,C-> B,D-> d,E->甲

到複印時切換細胞,你可以玩替換上面的最後一行,即

ws.Cells(pasteRow, "E").Value = rng.Cells(1, "B").Value 
ws.Cells(pasteRow, "B").Value = rng.Cells(1, "C").Value 
ws.Cells(pasteRow, "D").Value = rng.Cells(1, "D").Value 
ws.Cells(pasteRow, "A").Value = rng.Cells(1, "A").Value 

而是隻得到每個最後一行突出

我找不到原因,除了實際上有兩個區域,原因不明。

+1

謝謝@ A.S.H!我得到了我想要的! – Santa