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

pieyvz9o  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(1085)

我有一个包含多个单元格的区域,我想将该区域的字体颜色和内部颜色复制到另一个相同大小的区域中。我将使用以下代码进行测试:

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

不过,这并没有复制正确的颜色;两个目标单元格最终显示为黑色,这表明源单元格中的颜色值可能被加在了一起。
迭代范围中的每个单元格都可以,但是这种解决方案的伸缩性不好--我需要一种能够相当快地处理1,000,000+个单元格的解决方案。
编辑:我只想复制字体颜色和内部颜色--没有其他格式属性。

2hh7jdfx

2hh7jdfx1#

这里有一个解决偏移问题的不同方法。偏移是要粘贴到的range中第一个单元格的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

输出示例:

**编辑:**抱歉,没有读到您的最后一句话。下面是在不遍历单元格的情况下完成此操作的方法:

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

相关问题