首页 > 解决方案 > 在 VBA 中格式化和重置 excel 单元格的格式

问题描述

在下面的代码片段中,我在 excel 中使用了两个 activex 标签控件。拳头标签(称为 lblCellAddress) 我根据下面给出的预设值格式化所选单元格。第二个标签(称为 lblFormatEraser) 我将单元格的格式设置为默认值,因此它将所选单元格的格式转换为默认值。

Private Sub lblCellAddress_Click()
    'Format the Cells
    '--------------------
    With Selection
        .Font.Size = 12
        .Font.Bold = True
        .Font.Color = vbBlue
        .Font.Name = "Calibri"
        .Columns.AutoFit
        .Interior.Color = vbGreen
        .Borders.Weight = xlThick
        '.Borders.Weight = xlThin
        .Borders.Color = vbRed
        '.BackgroundColor = vbRed
    End With
    
    'Format the Label CellFormater
    '--------------------
    With lblCellAddress
        .BackColor = vbRed
        .BorderColor = vbGreen
        .BorderStyle = fmBorderStyleSingle
        .ForeColor = vbBlue
        .Font = Calibri
        .Shadow = True
        .TextAlign = fmTextAlignCenter
    End With
                  
  '  Range("A20").Select
End Sub
    'Erase the Cell Formats
    '--------------------
Private Sub lblFormatEraser_Click()
   With Selection
        .Font.Bold = False
        .Font.Color = vbBlack
        .Interior.Color = xlNone
        .Borders.LineStyle = xlNone
   End With
    
    'Format the Label CellFormater
    '--------------------
    With lblFormatEraser
        .BackColor = vbGreen
        .BorderColor = vbRed
        .BorderStyle = fmBorderStyleSingle
        .ForeColor = vbBlue
        .Font = Calibri
        .Shadow = True
        .TextAlign = fmTextAlignCenter
    End With
End Sub

标签: excelvbaformattingcell

解决方案


Private Sub lblCellAddress_Click()
    'Format the Cells
    '--------------------
    With Selection
        .Font.Size = 12
        .Font.Bold = True
        .Font.Color = vbBlue
        .Font.Name = "Calibri"
        .Columns.AutoFit
        .Interior.Color = vbGreen
        .Borders.Weight = xlThick
        '.Borders.Weight = xlThin
        .Borders.Color = vbRed
        '.BackgroundColor = vbRed
    End With
    
    'Format the Label CellFormater
    '--------------------
    With lblCellAddress
        .BackColor = vbRed
        .BorderColor = vbGreen
        .BorderStyle = fmBorderStyleSingle
        .ForeColor = vbBlue
        .Font = Calibri
        .Shadow = True
        .TextAlign = fmTextAlignCenter
    End With
                  
  '  Range("A20").Select
End Sub
    'Erase the Cell Formats
    '--------------------
Private Sub lblFormatEraser_Click()
   With Selection
        .Font.Bold = False
        .Font.Color = vbBlack
        .Interior.Color = xlNone
        .Borders.LineStyle = xlNone
   End With
    
    'Format the Label CellFormater
    '--------------------
    With lblFormatEraser
        .BackColor = vbGreen
        .BorderColor = vbRed
        .BorderStyle = fmBorderStyleSingle
        .ForeColor = vbBlue
        .Font = Calibri
        .Shadow = True
        .TextAlign = fmTextAlignCenter
    End With
End Sub

推荐阅读