VBA格式单元格填充颜色基于内容文件类型

时间:2017-02-08 11:12:59

标签: excel vba excel-vba colors conditional-formatting

我正在尝试在Excel列中读取文档列表,并根据文件类型更改单元格的颜色。但我不能这样做。有解决方案吗

Public Sub Master()

       Dim TdCel As Range, FCell As Range

       Set TdCel = Range("A1:A25")

       For Each FCell In TdCel

          If FCell.Text = "*.pdf" Then
                FCell.Interior.ColorIndex = 10
            ElseIf FCell.Value = "*.*.doc" Then
                FCell.Interior.ColorIndex = 9
            ElseIf FCell.Value = "*.jpg" Then
                FCell.Interior.ColorIndex = 8
            Else
                FCell.Interior.Color = vbWhite
          End If
       Next

    End Sub

3 个答案:

答案 0 :(得分:2)

几点改进:

  1. 定义您工作的工作表(在inputPassword
  2. 行中更改工作表的名称
  3. 使用Set wS = ...
  4. 使用WithSelect Case,降低案例单元格的值(Like
  5. 工作解决方案:

    LCase()

答案 1 :(得分:1)

编辑以缩短代码(并使@ R3uK更不受欢迎......)

你可以使用Switch()功能

Public Sub Master_JoaoTS()
    Dim FCell As Range
    Dim docType As String
    Dim clrIndex As Variant

    For Each FCell In Worksheets("myWorksheetName").Range("A1:A25").SpecialCells(xlCellTypeConstants, xlTextValues)
        With FCell
            docType = LCase(Right(.Value, Len(.Value) - InStrRev(.Value, ".")))
            clrIndex = Switch(docType = "pdf", 10, _
                             docType = "doc", 9, _
                             docType = "jpg", 8)
            If IsNull(clrIndex) Then clrIndex = 2
            .Interior.ColorIndex = clrIndex
        End With
    Next FCell
End Sub

答案 2 :(得分:0)

这是一个离原始代码不太远的解决方案,使用InStr函数查找子字符串" .pdf"," .doc"和" .jpg& #34;

Public Sub Master()

  Dim TdCel As Range, FCell As Range

  Set TdCel = Range("A1:A25")

  For Each FCell In TdCel

    If InStr(FCell, ".pdf") Then
      FCell.Interior.ColorIndex = 10
    ElseIf InStr(FCell, ".doc") Then
      FCell.Interior.ColorIndex = 9
    ElseIf InStr(FCell, ".jpg") Then
      FCell.Interior.ColorIndex = 8
    Else
      FCell.Interior.Color = vbWhite
    End If

  Next

End Sub