如何将表格1中的单元格复制到表格2而不删除表格2上的数据

正如我的标题所示,我需要代码来完成以下任务。 我已经尝试了很多不同的代码,但它仍然无法正常工作。 在这里输入图像说明 我只需要使用命令button将两列“SKU”和“Discount”移动到sheet2中,并立即删除。

我已经对这个编码好了。 但是,问题才刚刚开始。 在这里输入图像说明 当我成功移动第一个数据,并尝试移动第二个数据时,第一个数据消失。

我已经尝试了很多方法,但仍然无法弄清楚代码有什么问题。

请检查以下代码:

Sub OUTGOING_GOODS() function1 function2 clear Range_End_Method End Sub Sub function1() Sheets("Invoice Print").Range("B21:B27").Copy Destination:=Sheets("Outgoing Goods").Range("D4") End Sub Sub function2() Sheets("Invoice Print").Range("D21:D27").Copy Destination:=Sheets("Outgoing Goods").Range("L4") End Sub Sub clear() Range("B21:B27").clear End Sub 

我也需要改变input数据的范围。 正如你所看到的范围只是从D21:D27定义的,但我需要多于27行,以防万一有额外的数据input。

已经尝试了下面的代码:

  With Worksheets("Sheet2") LastRow = .Cells(.Rows.Count, "D").End(xlUp).Row LastRow = .Cells(.Rows.Count, "L").End(xlUp).Row For Each cell In Range("D4:D" & LastRow) DestinationRow = LastRow + 1 Next For Each cell In Range("L4:L" & LastRow) DestinationRow = LastRow + 1 Next End With 

 Lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row For i = 1 To InputData Lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row For j = 1 To 3 .Cells(lastrow + 1, j).Value = InputData(i, j) Next j Next i End With 

这仍然是行不通的。

根据我们迄今的讨论,我会build议如下:

 Sub Outgoing_Goods_New() ' Dim Outgoing As Worksheet 'Generally it's better to use Worksheet variables. Saves the trouble of having to re-type the sheet name each time you reference the sheet Dim Invoice As Worksheet Dim LastRow_Invoice As Long Dim LastRow_Outgoing As Long Set Outgoing = ActiveWorkbook.Worksheets("Outgoing Goods") Set Invoice = ActiveWorkbook.Worksheets("Invoice Print") 'Find the last row of Outgoing column D that's used so we know where to paste the new set of outgoing goods LastRow_Outgoing = Outgoing.Range("D1048576").End(xlUp).Row 'Make sure column L of Outgoing ends at the same point If Outgoing.Range("L1048576").End(xlUp).Row > LastRow_Outgoing Then LastRow_Outgoing = Outgoing.Range("L1048576").End(xlUp).Row End If 'else column L's last used row is farther up the worksheet or the same row. Either way no need to update the value 'Determine how much data to copy LastRow_Invoice = Invoice.Range("B1048576").End(xlUp).Row 'I'm assuming Column D of Invoice Print has to end at the same row. If not, use the same IF statement as above, but 'checking column D of Invoice 'Copy the data from column B Invoice.Range("B2:B" & LastRow_Invoice).Copy 'Paste to Outgoing Goods Outgoing.Range("B" & LastRow_Outgoing).PasteSpecial xlPasteAll 'Copy Column D of Invoice Invoice.Range("D2:D" & LastRow_Invoice).Copy Outgoing.Range("L" & LastRow_Outgoing).PasteSpecial xlPasteAll 'Clear the data from Invoice print Invoice.Range("B2:B" & LastRow_Invoice).ClearContents 'Removes the Value, but leaves formatting, comments, etc. alone End Sub 

这主要是你已经有的逻辑,但我做了一些清理,以消除歧义,逻辑一般化。 另外,请注意,我没有保留单独的Subs。 只要你做得很less,parsing逻辑就没有任何好处,特别是在没有任何代码被重用的情况下。

最后,我没有删除发票打印D列,假设单元格只是举行公式,根据列B中的值拉入新的数据。如果不是这样的话,似乎应该添加第二个ClearContents删除列D也是如此,但是由于你的用例含糊不清,这是不确定的。