簡體   English   中英

將值和顏色從一個工作簿復制到另一個工作簿而不復制條件格式

[英]Copy values and colors from one workbook to another without copying conditional formatting

我使用這行代碼將一個工作簿的內容復制到另一個,但它只復制值(避免得到#VALUE錯誤),但我希望也復制單元格的顏色:

Workbooks("Payroll Data.xlsm").Worksheets("Pay-MR Compiled").Range("A" & Total_rows_PayMRCompiled + 1 & ":BD" & Total_rows_PayMRCompiled + Total_rows_PayMR - 1).Value = ThisWorkbook.Worksheets("Pay-MR").Range("A2:BD" & Total_rows_PayMR).Value

我的問題是,當我復制Values & Source Formatting ,它還復制條件格式規則,因為我的條件是使用NOT(ISFORMULA(A2))函數來檢查單元格是否是公式,並且粘貼是只有值,所有都將被着色。

例如,實際數據中只突出顯示1個單元格,如下所示:

復制前

但是,使用Values and Source Formatting粘貼時會發生什么:

復制后

我認為沒有條件格式化就無法復制格式。
但是,您可以采用相反的方式:首先復制值和格式,然后刪除條件格式。

你的代碼看起來像

Dim destRange as Range
Set destRange = Workbooks("Payroll Data.xlsm").Worksheets("Pay-MR Compiled").Range("A" & Total_rows_PayMRCompiled + 1 & ":BD" & Total_rows_PayMRCompiled + Total_rows_PayMR - 1)

ThisWorkbook.Worksheets("Pay-MR").Range("A2:BD" & Total_rows_PayMR).Copy
destRange.PasteSpecial Paste:=xlPasteValues
destRange.PasteSpecial Paste:=xlPasteFormats
destRange.FormatConditions.Delete

如果目標上的顏色顯示不同,則兩個工作簿可能具有不同的顏色方案。 看看https://stackoverflow.com/a/37423390/7599798如何復制顏色設置。

站在你明確的條件格式公式,你可以試試這個

Set sourceRange = ThisWorkbook.Worksheets("Pay-MR").Range("A2:BD" & Total_rows_PayMR)        
With Workbooks("Payroll Data.xlsm").Worksheets("Pay-MR Compiled").Range(sourceRange.Address).Offset(Total_rows_PayMRCompiled - 1) ' reference "target" range
    .Value = sourceRange.Value ' paste "source" range values to referenced (i.e. "target") range
    .Interior.Color = sourceRange.FormatConditions(1).Interior.Color ' color referenced (i.e. "target") range with conditional formatting color
    .Parent.Range(sourceRange.SpecialCells(xlCellTypeFormulas).Offset(Total_rows_PayMRCompiled - 1).Address).Interior.Pattern = xlNone 'clear the color of "target" sheet range corresponding to "source" range cells with formulas 
End With

如果你的“源”的范圍的條件格式具有一個以上的公式,則只需改變1FormatConditions(1). 到正確的格式條件項目編號。


編輯以添加Total_rows_PayMRCompiled - 1目標范圍內的Total_rows_PayMRCompiled - 1行偏移

您可以使用.DisplayFormat方法實現此目的。 檢查一下

試試這樣吧

Set trgtCell = Workbooks("Payroll Data.xlsm").Worksheets("Pay-MR").Range("A2")
Set srcCell = ThisWorkbook.Worksheets("Pay-MR").Range("A2")

trgtCell.Value = srcCell.Value
trgtCell.Font.FontStyle = srcCell.DisplayFormat.Font.FontStyle
trgtCell.Interior.Color = srcCell.DisplayFormat.Interior.Color
trgtCell.Font.Strikethrough = srcCell.DisplayFormat.Font.Strikethrough
trgtCell.Font.Color = srcCell.DisplayFormat.Font.Color

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM