繁体   English   中英

Excel VBA从sheet1复制单元格并将其插入到标题sheet2中

[英]Excel VBA copy cells from sheet1 and insert them in header sheet2

我想从sheet1复制一些单元格,并将它们插入到sheet2的标题之间。 我在下面编写了代码并执行了一个按钮,但是问题是每次我单击按钮时,都会插入新的标题。 我该如何更改?

lastColumnS1 = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Column

Sheets("Sheet1").Select
Range(Cells(1, 3), Cells(1, lastColumnS1)).Select
Selection.Copy

Sheets("Sheet2").Select
lastColumn3 = ActiveSheet.Cells.SpecialCells(xlLastCell).Column
Range("B1").Select    
Selection.Insert Shift:=xlToRight  
Range(Cells(2, lastColumn3), Cells(3, lastColumn3)).Select
Selection.Cut
lastColumn3_ = ActiveSheet.Cells.SpecialCells(xlLastCell).Column
Range(Cells(2, lastColumn3_), Cells(3, lastColumn3_)).Select
ActiveSheet.Paste

样本数据

Sheet1:

ID   Name   x    y    z 
1    AA 
2    BB

Sheet2:

ID  Name
3   KK 
6   LL

desired result of Sheet2:

ID   x    y    z    Name
3                    KK
6                    LL

您用来获取最后使用的列的方法并不总是有效。 实际上,它似乎每次使用时都会增加。 以下内容将正确检索最后一列:

ActiveSheet.Cells.Find("*", SearchOrder:=xlByColumns, LookIn:=xlValues, SearchDirection:=xlPrevious).Column

暂无
暂无

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

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