简体   繁体   中英

Set Alignment of cell in range based on text value in cell

I'm new to VBA and I have a spreadsheet where I am trying to format the text to right align if the value in the cell equals "Total For The Month: ". I just need it to work for Worksheet1 in the workbook. If the value in cell C3 changes, I want the code to look through all the cells in column B and find any that equal "Total For The Month: " and right align it. However, my code isn't working. When I modify cell C3, nothing happens.

My code is as follows:


Dim SrchRng As Range, cel As Range

Set SrchRng = Range("$B1:$B1000")

If Target.Address = "C3" Then

For Each WS In Worksheets  
    With WS
        For Each cel In SrchRng  
            If InStr(1, cel.Value, "Total For The Month: ") > 0 Then  
                cel.HorizontalAlignment = xlRight  
            End If  
        Next cel  
    End With  
    Next WS  

End If

End Sub

As I don't know how to add a screenshot to a comment, I've decided to put this as an answer:

When you create a macro and you want to be sure it gets executed (or a certain line gets executed), you might add a breakpoint in the VBA editor, as you can see in this screenshot (just click in the left margin in order to add the breakpoint):

在此处输入图片说明

If the code is to be executed, the VBA editor pauzes there. If not, this piece of code is not executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM