Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying the cell value preserving the formatting from one cell to another in excel using VBA

In excel, I am trying to copy text from one cell to another cell in another sheet. The source cell contains formatted text (bold,underlined,different colors). But when I copy the text using VBA to the other cell, the formatting is lost.

I know it is because excel is copying only the text value. Is there a way we can read the HTML text (rather than plain text) from a cell?

I have googled this and did not get any answers. I know that if we use copy and paste methods, we can copy the formatting. E.g.

Range("F10").Select
Selection.Copy
Range("I10").Select
ActiveSheet.Paste

But I want to do it without a copy and paste since my destination is a merged cell and not identically sized as my source cell. Is there an option available in excel VBA to do this?

EDIT: I was able to solve it with the following code.

Range("I11").Value = Range("I10").Value
For i = 1 To Range("I10").Characters.Count
    Range("I11").Characters(i, 1).Font.Bold = Range("I10").Characters(i, 1).Font.Bold
    Range("I11").Characters(i, 1).Font.Color = Range("I10").Characters(i, 1).Font.Color
    Range("I11").Characters(i, 1).Font.Italic = Range("I10").Characters(i, 1).Font.Italic
    Range("I11").Characters(i, 1).Font.Underline = Range("I10").Characters(i, 1).Font.Underline
    Range("I11").Characters(i, 1).Font.FontStyle = Range("I10").Characters(i, 1).Font.FontStyle
Next i
like image 612
BlackCursor Avatar asked Aug 07 '12 15:08

BlackCursor


People also ask

How do I copy a cell value in Excel VBA?

We can copy a value and paste it to another cell. We can use Paste Special to paste only the values. Similarly, in VBA, we use the copy method with range property to copy a value from one cell to another. We use the worksheet function Paste Special or the paste method to paste the value.

How do you copy a value and format in Excel?

Select the cells that contain the data or other attributes that you want to copy. Click the first cell in the area where you want to paste what you copied. On the Home tab, under Edit, click Paste, and then click Paste Special. Paste all cell contents and formatting, including linked data.


1 Answers

Using Excel 2010 ? Try

Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
like image 190
Eric Avatar answered Oct 05 '22 07:10

Eric