更优雅的方式来取代文本和格式

现在我有这个:

[M3].select 'Range("M3").Select originally, I like using the [ ] notation totalrows = [H2].CurrentRegion.Rows.Count Range("m3:p" & totalrows).Select [m2].Activate 'Green With Application.ReplaceFormat.Interior .PatternColorIndex = xlAutomatic .Color = 5287936 End With Selection.Replace What:="Green", Replacement:="Red", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=True 

有没有更完美的方式来完成这个?

今天我发现了这一点,我喜欢它的简单性,并将其纳入其他处理文本replace的部分。

 [M:P].Replace "Green", "Red", xlPart 

但是,有一个简单的方法来设置单元格背景颜色为绿色,用这样的简单语句? 如果单元格包含文本“绿色”,请将单元格背景更改为绿色,并且不要更改文本。 感谢您的build议!

If the cell contains the text "Green", change the cell background to Green and don't change the text.

我会用这个我认为足够优雅的:

 [A1].FormatConditions.Add xlExpression, , "=A1=""Green""" With [A1].FormatConditions(1) .Interior.Color = RGB(0, 255, 0) .ModifyAppliesToRange [M:P] '~~> of course change this part to suit End With 

不是一个class轮,但。

偶然发现了这个收集灰尘,并认为一个小助手例行公事会很好地做到这一点。 ApplyBackgroundColor是没有什么奇特的 – 一个Select...Case陈述与一小部分的错误陷阱。 这里是我使用的颜色的链接,随时构build出更多的function: http : //dmcritchie.mvps.org/excel/colors.htm

 Option Explicit Public Sub ApplyBackgroundColor(Target As Range, Color As String) 'error trap, if target is empty then exit If Target Is Nothing Then Exit Sub With Target Select Case UCase(Color) Case Is = "GREEN" .Interior.ColorIndex = 4 Case Is = "RED" .Interior.ColorIndex = 3 Case Is = "BLUE" .Interior.ColorIndex = 5 Case Is = "YELLOW" .Interior.ColorIndex = 6 Case Else '<~ don't do anything if the string doesn't match End Select End With End Sub 

这是必须的testing程序,以确保它的工作:

 Sub TestApplyBackgroundColor() Dim MyRange As Range Set MyRange = Range(Cells(1, 1), Cells(5, 5)) Call ApplyBackgroundColor(MyRange, "Blue") '<~ not the most elegant, but an improvement End Sub