使用VBA将单元格值从一个单元格复制到另一个单元格 [英] Copying the cell value preserving the formatting from one cell to another in excel using VBA

查看:179
本文介绍了使用VBA将单元格值从一个单元格复制到另一个单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 excel 中,我试图将文本从一个单元格复制到另一个工作表中的另一个单元格.源单元格包含格式化文本(粗体、下划线、不同颜色).但是当我使用 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.

我知道这是因为 excel 只复制文本值.有没有办法我们可以从单元格中读取 HTML 文本 (而不是纯文本)?

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

但我不想复制和粘贴,因为我的目标是一个合并的单元格,并且与我的源单元格的大小不同.excel VBA 中是否有可用的选项来执行此操作?

我可以用下面的代码解决它.

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

推荐答案

复制格式:

Range("F10").Select
Selection.Copy
Range("I10:J10").Select ' note that we select the whole merged cell
Selection.PasteSpecial Paste:=xlPasteFormats

复制格式会破坏合并的单元格,因此您可以使用它来将单元格重新组合在一起

copying the formatting will break the merged cells, so you can use this to put the cell back together

Range("I10:J10").Select
Selection.Merge

要复制单元格值,而不复制任何其他内容(并且不使用复制/粘贴),您可以直接寻址单元格

To copy a cell value, without copying anything else (and not using copy/paste), you can address the cells directly

Range("I10").Value = Range("F10").Value

其他属性(字体、颜色、etc )也可以通过以相同方式直接寻址范围对象属性来复制

other properties (font, color, etc ) can also be copied by addressing the range object properties directly in the same way

这篇关于使用VBA将单元格值从一个单元格复制到另一个单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆