我尝试对此进行编程,所以当我创建一个保存为xlsx文件的工作簿时,我正在将工作簿中的vba从条件复制格式复制数据到新工作簿的sheet1中。我需要它具有公式A1 <> Sheet2!A1,然后文本字体为红色。然后下一个单元格将是B1 <> Sheet2“ B1文本字体为红色。
我需要将此复制到活动范围。我尝试了这段代码,但对我不起作用。花了两个星期的时间来寻找解决问题的方法。
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
答案 0 :(得分:0)
尝试以此替换所有代码:
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
希望所有帮助。抱歉,长度不够。