简体   繁体   中英

Excel to copy / paste some cells from one sheet to another but with a twist

I've made an invoice workbook that we use to print documents. I'm trying to make a list of sold products, client names and so on, based on what is typed in the invoice sheet. The list on sold items and client names are located on another sheet. After each time an invoice is printed, the workbook is saved, so that the invoice sheet can be cleared out and other data can be inserted. Basically, to copy data from the invoice to the list, i'm using the following piece of code:

Sheets("factura").Range("m14:m36").Copy
With Sheets("Centralizator").Range("C" & Rows.Count).End(xlUp).Offset(1)
    .PasteSpecial Paste:=xlPasteValues
     End With


Sheets("factura").Range("L2").Copy
With Sheets("Centralizator").Range("B" & Rows.Count).End(xlUp).Offset(1)    
    .PasteSpecial Paste:=xlPasteValues
     End With

Column C stores the products being sold and column B the names of the clients that bought them. The above code works well when a client has one coresponding product. However, if a client haves 2 or more products, the next time i run the code, the next client's name appears just underneath the previous one, in the same row with the products bought by the first client. Here's a picture with the problem.

Picture link 在此处输入图片说明

I would like to modify the code so that when i copy the client name from the invoice (factura) to column B, it will first find the first clear row on column C and using that row's number, paste the client name in the column b on that number. Something like this:

Picture link 在此处输入图片说明 Sorry for my bad english (not my native language) Could you please help me?

try this

Option Explicit

Sub UpdateCentralizator()
Dim lastRow As Long

lastRow = GetLastRow(Sheets("Centralizator"), 3) + 1
Sheets("factura").Range("m14:m36").SpecialCells(xlCellTypeConstants).Copy
Sheets("Centralizator").cells(lastRow, 3).PasteSpecial Paste:=xlPasteValues

Sheets("factura").Range("L2").Copy
Sheets("Centralizator").cells(lastRow, 1).PasteSpecial Paste:=xlPasteValues

End Sub


Function GetLastRow(sht As Worksheet, col As Long) as long
With sht
    GetLastRow = .cells(.Rows.Count, col).End(xlUp).row
    If IsEmpty(.cells(GetLastRow, col)) Then GetLastRow = 0
End With
End Function

the .SpecialCells(xlCellTypeConstants) method selects the only cells filled with constants (numbers or text), so that any empty cell of Sheets("factura").Range("m14:m36") would not be pasted into Sheets("Centralizator")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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