Excel使用macros更改列格式

如果在列名称中有单词COST,则使用macro for excel将列格式更改为货币。

如果列名是“最终成本”或“总成本”或“项目成本”,则将列格式更改为货币。

谢谢

尝试类似

Public Sub FormatCostColumnsAsCurrency() Dim sht As Worksheet Set sht = ActiveSheet Dim rng As Range Dim i As Integer For i = 1 To sht.UsedRange.Columns.Count Set rng = sht.Cells(1, i) If InStr(LCase(rng.Text), "cost") > 0 Then sht.Columns(i).NumberFormat = "$#,##0.00" End If Next End Sub 

您可以使用Conditional Formatting来做到这一点,不需要macros。

  1. 突出显示表格左列中的单元格。

  2. 在function区的“ Home部分,单击“ Conditional Formatting ,然后单击“ New Rule

  3. Use a formula to determine which cells to format

  4. input这个公式。 如果您的行标题不是以A1开头的,请相应地更改: =SEARCH("cost",A$1,1)

  5. 单击Format并将Number设置为Currency ,然后单击确定。

  6. 在“ Conditional Formatting Rules Manager ,将“ Applies to Conditional Formatting Rules Manager设置Applies to覆盖您的表格。

尝试下面的代码

 Sub CurrFormat() Dim colHeader As Range Set colHeader = Range("A1:E1") Dim currCell As Range Set currCell = Cells.Find("COST") If Not currCell Is Nothing Then currCell.NumberFormat = "$#,##0.00" End Sub