简体   繁体   English

VBA:复制并粘贴当前区域中的最后一行

[英]VBA : copy and paste last row in current region

My goal: 我的目标:
copy last row in every current region and paste them into A26 region. 复制每个当前区域中的最后一行并将其粘贴到A26区域中。
So A26 would be the first cell in that new region. 因此,A26将是该新区域中的第一个单元。
Also switching cell contents. 还切换单元格内容。
Notice that content in cell A = cell C in new range, 请注意,单元格A中的内容=新范围中的单元格C,
B->E, C->B, D->D, E->A. B-> E,C-> B,D-> D,E-> A。
Expected results is in the image below. 预期结果如下图所示。

Problem in current code: 当前代码中的问题:
I wasn't sure how to copy all cells and paste them into respective col. 我不确定如何复制所有单元格并将其粘贴到相应的col中。
Instead of getting ONLY each last row highlighted, 而不是仅将每一行都突出显示,
some of the current region got last 2 rows highlighted. 当前区域中的某些区域突出显示了最后两行。
Also the current code, only copy last row in the sheet as it was being overwritten in the loop? 还有当前代码,仅复制工作表中的最后一行,因为它在循环中被覆盖了吗?

预期成绩

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

I am still new to vba. 我还是vba的新手。 Can anybody shed me some light? 谁能给我一些启示?

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

Your code overwrites always the same row. 您的代码将始终覆盖同一行。 To avoid this you can change the above statements into 为了避免这种情况,您可以将以上语句更改为

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->A B-> E,C-> B,D-> D,E-> A

To switch cells when copying, you can play around replacing the last line above, ie 要在复制时切换单元格,可以尝试替换上面的最后一行,即

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

Instead of getting ONLY each last row highlighted 而不是仅将每最后一行突出显示

I couldn't find a reason for that, other than there were actually two areas, for an unknown reason. 除了一个实际原因,我实际上没有两个原因,我找不到原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM