如果值超过500,则将单元格的格式更改为粗体

时间:2014-02-18 16:33:18

标签: excel vba excel-vba

我正在使用Excel 2010并尝试添加一堆行,将列A和B的总和放在C列中。如果总和超过500,我会想要在C列中加粗数字。我的代码在下面工作以数学方式工作,但不会做粗体格式。有人能告诉我我做错了什么吗?谢谢。

Public Sub addMyRows()
    Dim row As Integer 'creates a variable called 'row'
    row = 2  'sets row to 2 b/c first row is a title
    Do
        Cells(row, 3).Formula = "=A" & row & "+B" & row 'the 3 stands for column C.
            If ActiveCell.Value > 500 Then Selection.Font.Bold = True
        row = row + 1

    'loops until it encounters an empty row
    Loop Until Len(Cells(row, 1)) = 0
End Sub

1 个答案:

答案 0 :(得分:2)

Pure VBA方法:

Public Sub AddMyRows()
    Dim LRow As Long
    Dim Rng As Range, Cell As Range
    LRow = Range("A" & Rows.Count).End(xlUp).Row
    Set Rng = Range("C2:C" & LRow)
    Rng.Formula = "=A2+B2"
    For Each Cell In Rng
        Cell.Font.Bold = (Cell.Value > 500)
    Next Cell
End Sub

<强>截图:

enter image description here

另一种选择是条件格式化。

希望这有帮助。

注意:块中的公式已经过编辑,以反映@ simoco关于重新运行代码的注释。这使得代码在需要重新运行时更安全。 :)