首页 > 解决方案 > 如果 Sheet1 中的单元格与 Sheet2 中的相同单元格不匹配,Excel vba 将插入条件格式

问题描述

我试图对此进行编程,因此当我创建一个保存为 xlsx 文件的工作簿时,工作簿中的 vba 我将数据从复制条件格式复制到新工作簿的 sheet1。我需要它有公式 A1 <> Sheet2!A1 然后文本字体是红色的。然后下一个单元格将是 B1 <> Sheet2"B1 文本字体为红色。

我需要将其复制到活动范围。我试过这段代码,但它对我不起作用。花了 2 周的时间试图找到答案,但没有任何乐趣。

Application.CutCopyMode =False

Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
    "=A1<>Sheet2!A1"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority

With Selection.FormatConditions(1).Font
    .Color =-16776961
    .TintAndShade =0
EndWith

Selection.FormatConditions(1).StopIfTrue =False
Selection.Copy
Range("A1:S200").Select
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
    SkipBlanks:=False, Transpose:=False

标签: vbaexcel

解决方案


尝试用以下代码替换所有代码:

Dim newCondition As FormatCondition 'Red text if Sheet1 cell doesn't match Sheet2 cell.
Dim conditionFormula As String      'Formula for the format condition

' Compare each cell using indirect addressing of the current row and column. Result is
' true if the sheet cells don't match, false if they do.
conditionFormula = "=(INDIRECT(ADDRESS(ROW(),COLUMN(),1,1,""Sheet1"")) <>" & _
                   "  INDIRECT(ADDRESS(ROW(),COLUMN(),1,1,""Sheet2"")))"

' Create the condition and get a pointer to it.
Set newCondition = Range("A1:S200").FormatConditions.Add( _
                                    Type:=xlExpression, _
                                    Formula1:=conditionFormula)

' Add the formatting, priority, stop rule to the condition.
With newCondition
    .SetFirstPriority
    With .Font
        .Color = -16776961  ' Red
        .TintAndShade = 0
    End With
    .StopIfTrue = False
End With

' Clear the pointer
Set newCondition = Nothing

当然,conditionFormula字符串声明不是必需的,但我喜欢编写以后易于阅读和理解的代码。我有太多次我稍后回来,想知道#@%*&!我试图做。

请注意,您可以使用ActiveSheet.UsedRange而不是Range("A1:S200"). 这将保证您始终获得所有具有数据的单元格。

最后,我还没有完全限定Range()我的代码中的方法。因此 Excel 会猜测您要使用哪个工作表。最好更明确地说明您正在谈论的工作簿和工作表。因此,例如,当您创建新工作簿时,请执行以下操作:

Dim newWorkbook As Workbook

Set newWorkbook = Workbooks.Open(.... whatever you do here...)

然后,您可以替换Range("A1:S200")

newWorkbook.Worksheets(1).Range("A1:S200")

甚至

newWorkbook.Worksheets(1).UsedRange

希望所有这些都有帮助。对不起,长度。


推荐阅读