Vba 更优雅的文本替换和格式设置方法

Vba 更优雅的文本替换和格式设置方法,vba,excel,Vba,Excel,现在我有这个: [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 .PatternColorInd

现在我有这个:

[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
有没有更优雅的方式来实现这一点

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

[M:P].Replace "Green", "Red", xlPart
但是,有没有一种简单的方法可以将单元格背景颜色设置为绿色?如果单元格包含文本“绿色”,请将单元格背景更改为绿色,不要更改文本。
谢谢你的建议

偶然发现了这个正在收集灰尘的人,并认为一个小助手程序会很好地完成这个任务
ApplyBackgroundColor
一点也不奇怪——一个带有一点点错误陷阱的
Select…Case
语句。以下是我使用的颜色链接,请随意构建更多功能:

选项显式
公共子ApplyBackgroundColor(目标作为范围,颜色作为字符串)
'错误陷阱,如果目标为空,则退出
如果目标为Nothing,则退出Sub
有目标
选择案例UCase(颜色)
Case Is=“绿色”
.Interior.ColorIndex=4
Case Is=“红色”
.Interior.ColorIndex=3
Case Is=“蓝色”
.Interior.ColorIndex=5
Case Is=“黄色”
.Interior.ColorIndex=6

Case Else'
如果单元格包含文本“绿色”,请将单元格背景更改为绿色,不要更改文本。

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

[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

但是没有一行。

我建议您使用
xlother
而不是
xlPart
。是的,建议不错。改变了我的项目&谢谢你,L42+1,这个函数在回答实际问题方面比我的函数做得更好,我的函数要求用户传入一个目标
范围
,以进行非常好的修改!但是,如果我将这些单元格移动/复制到另一个工作表中,格式是否会下降?我需要测试一下。谢谢你的代码,我一定会用的@不,你也可以复制和粘贴格式。重要的是你如何设置它。太棒了!谢谢,L42@海滩流浪汉68所以,我们用……向你表示感谢谢谢你,丹。这是一个伟大的惯例!我将把它添加到我的函数模块中,并试一试。看起来不错。我希望一切顺利。。。在这里找出一个真正好的问题很有趣!
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
[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