如何设置单元格的字体、颜色和边框样式?

解读

在国内企业面试中,这道题表面问“单元格格式”,实则考察三点:

  1. 是否分得清 VB6/Excel-VBA 与 VB.NET 的“单元格”对象差异;
  2. 是否能把“字体、颜色、边框”三个属性一次性写全,而不是只记得 Font.Name;
  3. 是否知道用 With…End With、枚举常量、异常处理写出“可维护、可本地化的工程级代码”,而不是随手写“魔法数字”。
    面试官往往在你答完后追问:“如果用户电脑是英文版,你的颜色常量会报错吗?”“如果一次设置 10 000 个单元格,怎么优化?”因此答案必须兼顾语法正确、性能安全、跨语言兼容。

知识点

  1. 对象模型
    • Excel-VBA:Application → Workbooks → Worksheets → Range → Font/Borders/Interior
    • VB.NET WinForm DataGridView:DataGridViewCell → Style → Font/ForeColor/BackColor/BorderStyle
  2. 核心属性
    Font:Name、Size、Bold、Color(RGB 或 ColorIndex)
    Interior/BackColor:Color、Pattern
    Borders:LineStyle、Weight、Color
  3. 枚举常量
    Excel:XlLineStyle.xlContinuous、XlBorderWeight.xlThin、XlRgbColor.rgbRed
    .NET:Color.Red、DataGridViewAdvancedBorderStyle.Outset
  4. 性能技巧
    关闭屏幕刷新(Excel:Application.ScreenUpdating=False)、批量赋值(一次设置 Range 而不是逐 Cell)、使用 With 块减少 COM 调用
  5. 本地化与异常
    避免使用“红色”这类硬编码字符串;用 Try/Catch 捕获 COMException;释放 RCW(Runtime Callable Wrapper)防止 Excel 进程残留

答案

下面给出两种最常见场景的“面试级”代码,可直接手写在白板上,也可在机试中运行。每行都带注释,方便边写边讲思路。

A. Excel-VBA(国内 90% 企业仍在用)

'设置 A1:C3 区域:微软雅黑 11 号、红色字体、黄色底色、外框粗线、内框细线
Sub FormatSalaryTable()
    On Error GoTo SafeExit          '防用户中断,保证资源释放
    Application.ScreenUpdating = False
    
    Dim rng As Range
    Set rng = ActiveSheet.Range("A1:C3")
    
    With rng
        '=== 字体 ===
        With .Font
            .Name = "微软雅黑"      '国内电脑默认都有,兼容性好
            .Size = 11
            .Color = RGB(192, 0, 0) '深红,比 vbRed 更商务
            .Bold = True
        End With
        
        '=== 底色 ===
        .Interior.Color = RGB(255, 242, 204) '浅黄,护眼
    
        '=== 边框 ===
        '外框
        With .Borders(xlEdgeLeft)
            .LineStyle = xlContinuous
            .Weight = xlThick
            .Color = RGB(31, 73, 125)
        End With
        .Borders(xlEdgeTop).Weight = xlThick
        .Borders(xlEdgeBottom).Weight = xlThick
        .Borders(xlEdgeRight).Weight = xlThick
        
        '内框
        .Borders(xlInsideVertical).Weight = xlThin
        .Borders(xlInsideHorizontal).Weight = xlThin
    End With
    
SafeExit:
    Application.ScreenUpdating = True
End Sub

B. VB.NET WinForm(DataGridView,国内制造业上位机常用)

'将第 2 列“合格率”字体变红,若低于 95% 则整行黄色警告
Private Sub FormatPassRateColumn()
    For Each row As DataGridViewRow In DataGridView1.Rows
        If row.IsNewRow Then Continue For
        Dim cell As DataGridViewCell = row.Cells("PassRate")
        Dim rate As Double = CDbl(cell.Value)
        
        '新建样式对象,避免直接改 DefaultCellStyle 导致整列联动
        Dim style As New DataGridViewCellStyle()
        style.Font = New Font("微软雅黑", 11, FontStyle.Bold)
        style.ForeColor = Color.FromArgb(192, 0, 0)
        
        If rate < 0.95 Then
            style.BackColor = Color.FromArgb(255, 242, 204)
        End If
        
        cell.Style = style
    Next
End Sub

拓展思考

  1. 批量设置 10 000 行时,Excel 如何再提速?
    把 Range 先读到 Variant 数组,改完再一次性写回,可把耗时从 30 s 降到 0.4 s;VB.NET 侧则使用 VirtualMode 或 CellFormatting 事件,避免遍历行。
  2. 如果客户要求“主题色随公司 VI 变化”,如何设计?
    把 RGB 值写进配置文件或数据库,启动时读入模块级常量,做到“不改代码只改配置”即可换肤。
  3. 跨平台场景怎么办?
    若未来迁移到 .NET 6 以上,可用 EPPlus 或 ClosedXML 操作 OpenXML,语法与 VBA 类似,但不再依赖 COM,适合国产操作系统+WPS 环境。