简体   繁体   中英

Excel VBA copy from sheet1 cell to sheet2 cell with format

I have a very simple problem but my lack of knowledge blocks me. I need to copy the values and the format of a cell from sheet1 to sheet2. The cell's row and column are changed by a loop. This works for me:

Sheets("SLAVE").Cells(slave_y, slave_x) = Sheets("MASTER").Cells(master_y, master_x)

but it only copies values and not formats.

I tried this

Sheets("MASTER").Cells(master_y, master_x).Copy Sheets("SLAVE").Cells(slave_y, slave_x)

but it copies me formulas (which I don't want)

Is there a way to specify to this line of code above to copy only values and formats?

Thank you!

Copy your values to clipoboard and then paste both, values and formats.

Sheets("MASTER").Cells(master_y, master_x).Copy
Sheets("SLAVE").Cells(slave_y, slave_x).PasteSpecial xlPasteFormats
Sheets("SLAVE").Cells(slave_y, slave_x).PasteSpecial xlPasteValues

We don't know how your ranges look like and if it is possible to copy/paste without loop. Maybe you can try something like this:

 Sub copy()

 With Application
      .ScreenUpdating = False
      .Calculation = xlCalculationManual
      .EnableEvents = False
      .DisplayStatusBar = False
 End With
 On Error Resume Next

 Dim mRng As Range   ' master Range
 Dim sRng As Range   ' slave Range

 Set mRng = ThisWorkbook.Sheets("masterSheetNameHere").Range("A1:A100")
 Set sRng = ThisWorkbook.Sheets("slaveSheetNameHere").Range("B1:B100")

 sRng.Value(11) = mRng.Value(11) ' 11 argument means values and formats

 On Error GoTo 0
 With Application
      .ScreenUpdating = True
      .Calculation = xlAutomatic
      .EnableEvents = True
      .DisplayStatusBar = True
 End With

 End Sub

UPDATE In your code (based on your file trial 07.xlsm) you have some possible performance issues. Eg instead:

 Sheets("MASTER").Range(Cells(j, MastCol1).Address()).Copy
 Sheets(nomeFoglio).Range(Cells(y, DestColE1).Address()).PasteSpecial Paste:=xlPasteColumnWidths

you can simply use:

 Sheets(nomeFoglio).Range(Cells(y, DestColE1).Address).ColumnWidth = Sheets("MASTER").Range(Cells(j, MastCol1).Address).ColumnWidth

Another more important issue is: do you really need apply your format cell by cell? It seems that your entire column has the same format. So you can possible use your fast code to copy values only and after all set format for entire columns (or in reverse order). One more thing- can't you copy range in row (3 cells in a row at once instead make copy operation for each cell)? The last one thing- if everything will not work, you should read about storing your data into an array and save from it into sheet at once.

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