更改每张纸的字体格式

时间:2016-10-16 18:25:19

标签: vba for-loop foreach fonts

我很想改变每张纸的字体大小。我还想在“E”列中的值低于18时将字体更改为粗体。

Dim ws As Worksheet

    ' Loop through all of the worksheets in the active workbook.
    For Each ws In ActiveWorkbook.Worksheets

        ' format font of currently looped worksheet object feferenced by WS
        With ws.Cells.Font
            .Name = "Calibri"
            .Size = 9
            .Strikethrough = False
            .Superscript = False
            .Subscript = False
            .OutlineFont = False
            .Shadow = False
            .Underline = xlUnderlineStyleNone
            .TintAndShade = 0
            .ThemeFont = xlThemeFontNone


            cr = ws.Cells(.Rows.Count, "A").End(xlUp).Row

            If Cells(cr, 5).Value < 18 Then
                Selection.Font.Bold = True
            End If

        End With

    Next ws

我有任何提示来解决问题。

我在这一行收到 错误438

    cr = .Cells(.Rows.Count, "A").End(xlUp).Row

我也试过

    cr = ws.Cells(.Rows.Count, "A").End(xlUp).Row

两个代码都无效......帮助

2 个答案:

答案 0 :(得分:1)

你有什么错误? 我认为上面的代码会改变字体大小。但是,将值小于18的单元格的代码更改字体变为粗体不起作用。

如果应用规则,您想将每个单元格更改为粗体,对吗? 尝试&#34;条件格式化&#34; (将应用每个单元格值更改和&lt; 18)或修改您的代码(每次运行宏时都会应用):

...
Dim i as integer
cr = ws.Cells(.Rows.Count, "A").End(xlUp).Row
For i = 1 to cr 'loop through all value in column e
       If .cells(i,5).value <18 then .cells(i,5).font.bold = true
Next i
....

答案 1 :(得分:0)

我修正了答案:

' Declare Current as a worksheet object variable.
Dim ws As Worksheet

    ' Loop through all of the worksheets in the active workbook.
    For Each ws In ActiveWorkbook.Worksheets

        ' format font of currently looped worksheet object feferenced by WS
        With ws
            .Cells.Font.Name = "Calibri"
            .Cells.Font.Size = 9
            .Cells.Font.Strikethrough = False
            .Cells.Font.Superscript = False
            .Cells.Font.Subscript = False
            .Cells.Font.OutlineFont = False
            .Cells.Font.Shadow = False
            .Cells.Font.Underline = xlUnderlineStyleNone
            .Cells.Font.TintAndShade = 0
            .Cells.Font.ThemeFont = xlThemeFontNone

            cr = .Cells(.Rows.Count, "A").End(xlUp).Row
            For i = 1 To cr 'loop through all value in column e
                   If .Cells(i, 5).Value < 18 Then .Cells(i, 5).Font.Bold = True
            Next i

        End With

    Next ws