【问题标题】:How to copy font and interior color from one multi-cell range to another?如何将字体和内部颜色从一个多单元格范围复制到另一个?
【发布时间】:2015-06-23 22:11:21
【问题描述】:

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

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 多个单元格的东西。

编辑:我只想复制字体颜色和内部颜色——没有其他格式属性。

【问题讨论】:

  • sht.Range("c1").value = "def" 中的c1 应该是b1
  • @JLILIAmen,不,它在c1 中显示字体颜色是否正确复制。

标签: vba excel


【解决方案1】:

这是使用偏移量解决问题的另一种方法。您的偏移量是要粘贴到的范围的第一个单元格的 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

【讨论】:

  • 我不能只粘贴格式;我只想复制颜色。我将编辑我的问题以澄清这一点。
  • 你需要多长时间才能遍历细胞?
  • 对于 10,000 个单元格,大约需要 40 秒。
猜你喜欢
  • 1970-01-01
  • 2014-04-09
  • 1970-01-01
  • 2019-01-24
  • 2019-11-22
  • 2013-10-28
  • 2018-01-15
  • 1970-01-01
  • 2015-02-16
相关资源
最近更新 更多