More elegant way of replacing text and formatting it

前端 未结 2 1024
庸人自扰
庸人自扰 2021-01-14 15:58

Right now I have this:

[M3].select \'Range(\"M3\").Select originally, I like using the [ ] notation
totalrows = [H2].CurrentRegion.Rows.Count
Range(\"m3:p\"          


        
相关标签:
2条回答
  • 2021-01-14 16:10

    Stumbled upon this one collecting dust and thought a little helper routine would do the trick nicely. ApplyBackgroundColor is nothing fancy -- a Select...Case statement with a tiny morsel of error trapping. Here is a link to the colors I used, feel free to build out more functionality: 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
    

    And here's the obligatory test routine to make sure it works:

    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
    
    0 讨论(0)
  • 2021-01-14 16:11

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

    I'd use this which I think is elegant enough:

    [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
    

    Not one liner though.

    0 讨论(0)
提交回复
热议问题