遍历单元格并更改字体

时间:2020-01-03 15:58:42

标签: excel vba fonts size

我试图遍历一行中的所有单元格并使用以下条件更改字体大小:

  • 如果字体大小小于10,则将字体大小更改为10

如果工作表中的所有单元格都具有相同的字体大小,则此方法有效。如果工作表中的任何单元格具有不同的字体大小,它将返回null。如果我在A1中的字体大小为8,在A2中的字体大小为20,则没有变化。

Sub SetSheetFont(ws As Worksheet)
    Dim x As Integer
    Dim NumRows As Long
    Application.ScreenUpdating = False
    NumRows = Range("A1", Range("A1").End(xlDown)).Rows.Count
    Range("A1").Select
    With ws
        ' If the font size is lower than 10, set to 10
        For x = 1 To NumRows
            If .Cells.Font.Size < 10 Then .Cells.Font.Size = 10
            ActiveCell.Offset(1, 0).Select
        Next
        Application.ScreenUpdating = True
    End With
End Sub

最终目标是循环遍历该列中的所有单元格,直到有一定数量的空单元格,然后从下一列开始(在本例中为B1)。

至少要在一栏内完成这项工作吗?我很确定,如果我从那里开始,我就能使它工作。

3 个答案:

答案 0 :(得分:3)

您可以遍历UsedRange

中的所有单元格
Sub SetSheetFont(ws As Worksheet)
    Dim myCell As Range
    Application.ScreenUpdating = False
    With ws
        For each myCell in ws.UsedRange
            ' If the font size is lower than 10, set to 10
            If myCell.Font.Size < 10 Then myCell.Font.Size = 10
        Next
    End With
    Application.ScreenUpdating = True
End Sub

旁注:通常,您想在代码中avoid using select

答案 1 :(得分:3)

根据我的评论,我认为这可能是FindFormatReplaceFormat的好用例:

Dim x As Double

'Set ReplaceFormat just once
Application.ReplaceFormat.Clear
Application.ReplaceFormat.Font.Size = 10

'Set FindFormat in a For loop
For x = 1 To 9.5 Step 0.5
    Application.FindFormat.Clear
    Application.FindFormat.Font.Size = x
    ws.Cells.Replace What:="", Replacement:="", SearchFormat:=True, ReplaceFormat:=True
Next x

这可防止在所有ws.Cells上进行迭代。循环是必需的,因为我们不能设置类似Application.FindFormat.Font.Size < 10的内容。而且由于Font.Size(至少对我来说)会自动调整为最接近的0.5(并且最小尺寸为1),因此我们可以从0.5逐步调整为1至9.5。

根据您的描述,您可能希望按照上述@ cybernetic.nomad将其更改为ws.UsedRange。因此它将显示为:ws.UsedRange.Replace...

答案 2 :(得分:2)

保留已注释的代码,您希望访问每个单元格(不是所有单元格,这是.Cells.的作用:

For x = 1 To NumRows
    If .Cells(x,1).Font.Size < 10 Then .Cells(x,1).Font.Size = 10
Next

这将循环到A列。(1中的.Cells(x,1))。

我还建议您使用.End(xlUp)代替xlDown,如果您的A列有一个空白行分隔Data。如果可以的话,您可以保留它...另一种选择是:NumRows = Range("A" & rows.count).End(xlUp).row(也可以将Long的{​​{1}}用于:

x

编辑:为确保确定,Sub SetSheetFont(ws As Worksheet) Dim x As Long, NumRows as Long Application.ScreenUpdating = False With ws NumRows = .Range("A" & rows.count).End(xlUp).Row ' If the font size is lower than 10, set to 10 For x = 1 To NumRows If .Cells(x,1).Font.Size < 10 Then .Cells(x,1).Font.Size = 10 Next Application.ScreenUpdating = True End With End Sub 将起作用,只是请注意它将在第一个空单元格处停止。像我一样使用xlDown,将确保在A列中获得所有行……这可能是您想要的,也可能不是。