使用vlookup参考在VBA中粘贴单元格颜色

时间:2018-08-12 21:35:32

标签: excel excel-vba

我正在研究用于创建组织结构图的代码,并且希望能够将表中源单元格的颜色粘贴到组织结构图中。当前,目标单元格格式是从预设格式(“ chartformat”)驱动的。下面的代码。任何帮助将不胜感激。

' Put Preformula

Range("preformula").Copy
Range("finalarea").PasteSpecial Paste:=xlPasteFormulas
Application.CutCopyMode = False
Sheets("Org Chart").Calculate

' Clear Blanks

Range("finalarea").SpecialCells(xlCellTypeFormulas, 4).ClearContents

' Put Format

Range("chartformat").Copy
Range("finalarea").SpecialCells(xlCellTypeFormulas, 2).PasteSpecial Paste:=xlPasteFormats


' Put Formula and Clear

Range("chartformula").Copy
Range("finalarea").PasteSpecial Paste:=xlPasteFormulas
Sheets("Org Chart").Calculate

Range("finalarea").Copy
Range("finalarea").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False

2 个答案:

答案 0 :(得分:0)

您是否在粘贴公式后尝试过粘贴格式?

Range("chartformula").Copy
Range("finalarea").PasteSpecial xlPasteFormulas
Range("finalarea").PasteSpecial xlPasteFormats
Sheets("Org Chart").Calculate

您还应该用一张纸来修饰Range,尤其是 ,因为您的宏不仅限于一张纸。

答案 1 :(得分:0)

认为这是您要执行的操作。

Sub main()

Dim ws                          As Worksheet
Dim wsTwo                       As Worksheet
Dim presetRange                 As Range
Dim finalArea                   As Range
Dim cell                        As Range

    Set ws = Sheets("Sheet1")
    Set wsTwo = Sheets("Sheet2")
    Set presetRange = wsTwo.Range("presetRange")
    Set finalArea = ws.Range("finalArea")

    finalArea.Clear
    finalArea.Formula = presetRange.Formula
    presetRange.Copy
    finalArea.PasteSpecial xlPasteFormats
    Application.CutCopyMode = False

    For Each cell In finalArea
        cell.Formula = "=Sheet2!" & Replace(cell.Formula, "=", "")
    Next cell
End Sub

enter image description here

enter image description here