请求编写VBA代码:将Sheet1指定单元格复制到Sheet2指定列并按行排列
VBA Solution for Targeted Cell Copy-Paste Between Sheets
Sure thing! Here's a clean VBA solution that handles your specific cell copying and mapping between Sheet1 and Sheet2, keeping everything on the same target row. I've included both a fast value-only method and a copy-paste method (if you need to retain formatting/formulas):
Sub CopySpecificCellsToSheet2() ' Define worksheet objects for easier reference Dim sourceSheet As Worksheet Dim destSheet As Worksheet Dim targetRow As Long ' Set references to your sheets (change names if needed) Set sourceSheet = ThisWorkbook.Worksheets("Sheet1") Set destSheet = ThisWorkbook.Worksheets("Sheet2") ' Set the row number in Sheet2 where you want to paste the data ' Adjust this to your desired row (e.g., 5 for row 5, or use ActiveCell.Row for the selected row) targetRow = 5 ' OPTION 1: Fast value transfer (no clipboard, only copies cell values) destSheet.Cells(targetRow, "A").Value = sourceSheet.Range("AA5").Value destSheet.Cells(targetRow, "B").Value = sourceSheet.Range("AA6").Value destSheet.Cells(targetRow, "D").Value = sourceSheet.Range("AA7").Value destSheet.Cells(targetRow, "F").Value = sourceSheet.Range("AA8").Value destSheet.Cells(targetRow, "G").Value = sourceSheet.Range("AA10").Value ' OPTION 2: Copy-paste (retains formatting, formulas, etc. uses clipboard) ' Uncomment the lines below if you need this instead of Option 1 ' sourceSheet.Range("AA5").Copy Destination:=destSheet.Cells(targetRow, "A") ' sourceSheet.Range("AA6").Copy Destination:=destSheet.Cells(targetRow, "B") ' sourceSheet.Range("AA7").Copy Destination:=destSheet.Cells(targetRow, "D") ' sourceSheet.Range("AA8").Copy Destination:=destSheet.Cells(targetRow, "F") ' sourceSheet.Range("AA10").Copy Destination:=destSheet.Cells(targetRow, "G") End Sub
How to Use This Code:
- Open your Excel file and press
Alt + F11to launch the VBA Editor. - Right-click your workbook name in the Project Explorer pane → Insert → Module.
- Paste the code into the new module window.
- Adjust the
targetRowvalue to match the row in Sheet2 where you want the data pasted. - Run the macro: Press
F5in the editor, or go back to Excel, open the Developer tab, click Macros, selectCopySpecificCellsToSheet2, and hit Run.
Notes:
- Using Option 1 (direct value assignment) is faster and avoids cluttering the clipboard, but only copies cell values.
- Use Option 2 (copy-paste) if you need to preserve things like cell formatting, conditional formatting, or formulas from the source cells.
内容的提问来源于stack exchange,提问作者Lenn90
相关产品推荐
相关产品推荐

