如何根据列标题设置单个单元格的格式?

时间:2019-05-20 03:58:35

标签: excel vba

我有一个表,该表的第一行具有标题,第二行具有单位类型。这些单位类型是$,%之类的值。

我想对单元格应用数字格式和四舍五入。

我下面的代码读取该列并将格式应用于单元格,但是我无法弄清楚如何舍入数字。有什么建议么?谢谢

Sub Format()

Dim lngCol As Long, i As Long
Dim str As String

lngCol = Cells(2, Columns.Count).End(xlToLeft).Column

For i = 1 To lngCol
    Select Case Cells(2, i)
        Case "$": Columns(i).Style = "Currency"
        Case "%": Columns(i).Style = "Percent"
End Select
Next

End sub

1 个答案:

答案 0 :(得分:1)

尝试类似的方法,您可以根据需要对其进行修改...

Public Sub FormatCellsBasedOnString()
    Dim lngToCol As Long, lngCol As Long, lngToRow As Long

    With Sheet1
        lngToCol = .Cells(1, .Columns.Count).End(xlToLeft).Column

        For lngCol = 1 To lngToCol
            lngToRow = .Cells(.Rows.Count, lngCol).End(xlUp).Row
            .Range(.Cells(3, lngCol).Address & ":" & .Cells(lngToRow, lngCol).Address).NumberFormat = .Cells(2, lngCol)
        Next
    End With
End Sub

它使用列第二行中的数字格式来格式化其下面的单元格。的选择是无止境的。将单元格格式化为所需的格式,然后转到单元格格式中的自定义,并使用该字符串使用该宏概念来格式化单元格。

enter image description here

我希望这是有道理的。