简体   繁体   English

根据单元格中的文本值设置范围内单元格的对齐方式

[英]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: ".我是 VBA 新手,我有一个电子表格,如果单元格中的值等于“本月总计:”,我试图将文本格式设置为右对齐。 I just need it to work for Worksheet1 in the workbook.我只需要它为工作簿中的 Worksheet1 工作。 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.如果单元格 C3 中的值发生变化,我希望代码查看 B 列中的所有单元格并找到任何等于“本月总计:”的值,然后将其右对齐。 However, my code isn't working.但是,我的代码不起作用。 When I modify cell C3, nothing happens.当我修改单元格 C3 时,没有任何反应。

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):当您创建一个宏并希望确保它被执行(或某行被执行)时,您可以在 VBA 编辑器中添加一个断点,正如您在此屏幕截图中看到的(只需单击左边距即可添加断点):

在此处输入图片说明

If the code is to be executed, the VBA editor pauzes there.如果要执行代码,VBA 编辑器会在那里暂停。 If not, this piece of code is not executed.如果不是,则不执行这段代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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