プロが教えるわが家の防犯対策術!

こんにちは、画像のように左のブックから、右の別のブックに枠線と値を転記しています。

ここまでは問題なく動作しているのですが、コピー元のセルに一部背景色がついています。

ペースト先では値しか存在しないため、条件付き書式を再設定するのは合理的ではない為、コピー元で付いた背景色も同時に移植する方法はありますか?

ちなみに動作しているコードは以下のようなものです。
既に正常動作していますので、これを流用して実現できればと思います。

詳しい方、よろしくお願いいたします。

Sub CopyToNewbook()
Dim lastRow As Long
Dim wb As Workbook
Dim ws As Worksheet
Dim sourceRange As Range
Dim destRange As Range

'Get the last used row in column BP
lastRow = ActiveSheet.Cells(Rows.Count, "BP").End(xlUp).Row

'Set the source range from U3 to BP last row
Set sourceRange = Range("U3:BP" & lastRow)

'Open the Asahi Shimoitozu Mirror.xlsm file
Set wb = Workbooks.Open("C:\Users\〇〇〇\Documents\Newbook.xlsm")

'Set the destination range in the first sheet of the opened workbook to match the size of the source range
Set ws = wb.Sheets(1)
Set destRange = ws.Range("A1").Resize(sourceRange.Rows.Count, sourceRange.Columns.Count)

'Copy the values and formatting from the source range to the destination range
sourceRange.Copy
destRange.PasteSpecial xlPasteValuesAndNumberFormats
destRange.PasteSpecial xlPasteFormats

'Auto-fit the columns in the destination range
destRange.EntireColumn.AutoFit

'Activate the destination workbook and save it
wb.Activate
wb.Save

End Sub

「エクセル 値をコピペした時に、条件付き書」の質問画像

質問者からの補足コメント

  • 失礼しました、元の背景色は条件付き書式にて設定された背景色です。

      補足日時:2023/04/05 17:31

A 回答 (2件)

こんにちは



セルの表示されている色(=条件付き書式の結果も含めて)は
 Cell.DisplayFormat.Interior.Color
で取得することが可能です。

Cell1の表示色をCell2の背景色として設定するには、
 Cell2.Interior.Color = Cell1.DisplayFormat.Interior.Color
とすることで可能です。

ただし、値とは異なり、セル範囲でまとめて取得するようなことはできませんので、範囲内の個々のセルをループして転記することが必要になります。

※ 余談ながら、DisplayFormat はユーザー定義関数では利用できませんのでご注意ください。
https://learn.microsoft.com/ja-jp/office/vba/api …
    • good
    • 0
この回答へのお礼

ありがとう

ありがとうございます。
出来る事が解ってほっとしています。

お礼日時:2023/04/05 17:52

コピー元の背景色をコピー先に移植するには、コピー先に背景色を設定する必要があります。

以下は、コピー元の背景色を取得し、コピー先に設定する方法です。既存のコードに追加することができます。

'Set the source range from U3 to BP last row Set sourceRange = Range("U3:BP" & lastRow)

'Copy the values, formatting, and background color from the source range to the destination range sourceRange.Copy destRange.PasteSpecial xlPasteValuesAndNumberFormats destRange.PasteSpecial xlPasteFormats For Each cell In sourceRange destRange.Cells(cell.Row - 2, cell.Column - 20).Interior.Color = cell.Interior.Color Next cell

'Auto-fit the columns in the destination range destRange.EntireColumn.AutoFit

'Activate the destination workbook and save it wb.Activate wb.Save

このコードは、コピー元のセルの背景色を取得し、その色をコピー先の対応するセルに設定します。また、既存のコードと同様に、値と書式もコピーするために、xlPasteValuesAndNumberFormatsとxlPasteFormatsを使用しています。
    • good
    • 0
この回答へのお礼

回答ありがとうございます。

ChatGPTで調べたコードを正しいかどうかもわからないのに回答するのはやめて下さい。

そういうのやらないほうが良いですよ、信用無くすんで。

お礼日時:2023/04/05 18:26

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!