简体   繁体   English

如何将字体和内部颜色从一个多单元格范围复制到另一个?

[英]How to copy font and interior color from one multi-cell range to another?

I have a range with several cells, and I want to copy that range's font colors and interior colors to another range of the same size.我有一个包含多个单元格的范围,我想将该范围的字体颜色和内部颜色复制到另一个相同大小的范围。 I'm using this code to test:我正在使用此代码进行测试:

Sub testColorCopy()

Dim sht As Worksheet
Dim rng As Range
Dim rng2 As Range

Set sht = ThisWorkbook.Sheets("Sheet1")
sht.Range("a1").value = "abc"
sht.Range("c1").value = "def"
sht.Range("a1").Font.ColorIndex = 3
sht.Range("b1").Interior.ColorIndex = 4

Set rng = sht.Range("a1:b1")
Set rng2 = sht.Range("c1:d1")

rng2.Interior.color = rng.Interior.color
rng2.Font.color = rng.Font.color


End Sub

This doesn't copy the correct colors, though;但是,这不会复制正确的颜色; the two destination cells end up black, suggesting that maybe the color values from the source cells were added together?两个目标单元格最终变成黑色,这表明源单元格的颜色值可能加在一起了吗?

Iterating through each cell in the range works, but that solution doesn't scale well--I need something that will handle 1,000,000+ cells reasonably quickly.迭代范围内的每个单元格都有效,但该解决方案不能很好地扩展——我需要一些能够相当快地处理 1,000,000+ 个单元格的东西。

EDIT: I only want to copy font color and interior color--no other formatting properties.编辑:我只想复制字体颜色和内部颜色——没有其他格式属性。

Here's a different approach to your problems using offsets.这是使用偏移量解决问题的不同方法。 Your offset is the rowid and colid of the first cell of range to be pasted onto.您的偏移量是要粘贴到的范围的第一个单元格的 rowid 和 colid。

  Sub testColorCopy()

    Dim sht As Worksheet
    Dim rng As Range
    Dim rng2 As Range

    Set sht = ThisWorkbook.Sheets("Feuil1")
    sht.Range("a1").Value = "abc"
    sht.Range("b1").Value = "def"
    sht.Range("a1").Font.ColorIndex = 3
    sht.Range("b1").Interior.ColorIndex = 4

    Set rng = sht.Range("a1:b1")

    Dim rowoffset As Long: rowoffset = 0
    Dim coloffset As Long: coloffset = 2

    For Each cell In rng
    cell.Offset(rowoffset, coloffset).Interior.ColorIndex = cell.Interior.ColorIndex
    cell.Offset(rowoffset, coloffset).Font.ColorIndex = cell.Font.ColorIndex
    Next cell


End Sub

Example output:示例输出:

在此处输入图片说明

Edit: Sorry, did not read your last sentence.编辑:对不起,没有阅读你的最后一句话。 Here's how it is done without iterating through the cells:这是在不遍历单元格的情况下完成的方法:

Sub testColorCopy()

Dim sht As Worksheet
Dim rng As Range
Dim rng2 As Range

Set sht = ThisWorkbook.Sheets("Feuil1")
sht.Range("a1").Value = "abc"
sht.Range("b1").Value = "def"
sht.Range("a1").Font.ColorIndex = 3
sht.Range("b1").Interior.ColorIndex = 4

Set rng = sht.Range("a1:b1")
Set rng2 = sht.Range("c1:d1")

rng.Copy
rng2.Parent.Activate
rng2.PasteSpecial xlPasteFormats
Application.CutCopyMode = False

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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