简体   繁体   English

如何在Excel VBA中将所有单元格颜色从一个工作簿复制到另一工作簿?

[英]How to copy all cell colors from one workbook to another in Excel VBA?

I have two large workbooks with identical sheet names, and similar data. 我有两个具有相同工作表名称和相似数据的大型工作簿。 The source sheet has a bunch of colors applied to the cells, and I have to copy those colors to their respective cells in the destination sheet. 源工作表将一堆颜色应用于单元格,我必须将这些颜色复制到目标工作表中的相应单元格。

I've tried this suggestion: How to copy an Excel color scheme from one workbook to another 我尝试过以下建议: 如何将Excel配色方案从一个工作簿复制到另一个工作簿

But it didn't seem to do anything. 但这似乎无能为力。

This is the code I wrote, but it locks up excel for a long time. 这是我编写的代码,但是很长一段时间都锁定了excel。 Does it look right to you? 它看起来合适吗?

Sub CopyColors()

Dim x As Workbook
Dim y As Workbook
Dim SomeSheet As Worksheet
Dim SomeRange As Range

Set x = Workbooks.Open(" c:/PATH/Source.xlsm ")
Set y = Workbooks.Open(" c:/PATH/Destination.xlsm ")

y.Colors = x.Colors

For Each SomeSheet In x.Worksheets
    For Each SomeRange In SomeSheet.Cells
        y.Sheets(SomeSheet.Name).Range(SomeRange.Address).Interior.ColorIndex = SomeRange.Interior.ColorIndex
    Next SomeRange
Next SomeSheet

End Sub

I decided it'd be a better use of my time to explore other options than to wait for this to pan out. 我决定,与等待该计划成功相比,将是更好地利用我的时间来探索其他选择。 If I don't get a better idea, I'll let this run overnight tonight. 如果我没有更好的主意,请让它在今晚通宵运行。

You may be able to adapt this to sheets in different workbooks. 您可能可以将其适应不同工作簿中的工作表。 Say we have two sheet in the same workbook. 假设我们在同一工作簿中有两张纸。 We want to copy the colors. 我们要复制颜色。 Rather than looping of all the cells individually, we copy all the cells from the first sheet and and PasteSpecialFormats into the second worksheet: 我们不是将所有单元格单独循环,而是将第一张工作表中的所有单元格和PasteSpecialFormats复制到第二个工作表中:

From the Recorder: 从记录器:

Sub Macro2()
    Sheets("Sheet1").Select
    Cells.Select
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("Sheet2").Select
    Cells.Select
    Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
        SkipBlanks:=False, Transpose:=False
End Sub

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

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