首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >更优雅的替换文本和格式化文本的方法

更优雅的替换文本和格式化文本的方法
EN

Stack Overflow用户
提问于 2014-03-19 17:34:27
回答 2查看 198关注 0票数 3

现在我有一个:

代码语言:javascript
运行
复制
[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

有什么更优雅的方法来完成这个任务吗?

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

代码语言:javascript
运行
复制
[M:P].Replace "Green", "Red", xlPart

但是,有一种简单的方法可以用这样的简单语句将细胞背景颜色设置为绿色吗?如果单元格包含文本“绿色”,则将单元格背景更改为“绿色”,不更改文本。谢谢你的建议!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-05-20 06:54:15

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

我会用它,我认为它足够优雅:

代码语言:javascript
运行
复制
[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

不过,没有一条班轮。

票数 1
EN

Stack Overflow用户

发布于 2014-05-20 00:33:58

偶然发现了这个收集灰尘,并认为一个小帮手的例行工作,可以很好地发挥作用。ApplyBackgroundColor不是什么稀奇古怪的东西--一条带有少量错误陷阱的Select...Case语句。这里有一个指向我使用的颜色的链接,可以自由构建更多功能:http://dmcritchie.mvps.org/excel/colors.htm

代码语言:javascript
运行
复制
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

下面是确保其工作正常的强制性测试例程:

代码语言:javascript
运行
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22513772

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档