如果只有单元格内容特定值,则使脚本工作

问题描述 投票:0回答:1

我正在尝试让 VB 脚本检查所有单元格并为它着色(如果它具有特定值) 例如:“1”将其遮蔽为绿色而不是 12 或带数字的文字

Sub CheckTableCellContent()
    Dim tbl As table
    Dim row As row
    Dim cell As cell
    
    For Each tbl In ActiveDocument.Tables
        For Each row In tbl.Rows
            For Each cell In row.Cells
                If cell.Range.Text Like "*1*" Then
                    cell.shading.BackgroundPatternColor = RGB(0, 176, 80)
               ElseIf cell.Range.Text Like "*2*" Then
                    cell.shading.BackgroundPatternColor = RGB(146, 208, 80)
               ElseIf cell.Range.Text Like "*3*" Then
                    cell.shading.BackgroundPatternColor = RGB(255, 255, 0)
             ElseIf cell.Range.Text Like "*4*" Then
                    cell.shading.BackgroundPatternColor = RGB(255, 0, 0)
                    
        
                End If
            Next cell
        Next row
    Next tbl
    
End Sub

它的颜色是任何单元格都有 1 而不是只有 1 并且与其余单元格相同

ms-word vbscript
1个回答
0
投票

*1*
模式(参见Like Operator)将匹配任何包含 1 的字符串。
abc1def
21
都会匹配,从你的问题来看,这听起来不像你想要做的。

为了给只有

1
的单元格上色,你可以使用“1”作为你的模式:

cell.Range.Text Like "1"

当我测试这个时,我注意到单元格文本中还有其他字符,所以我修改了代码以在检查值之前将它们删除:

Sub CheckTableCellContent()
    Dim tbl As Table
    Dim row As row
    Dim cell As cell
    Dim cellText As String
    
    For Each tbl In ActiveDocument.Tables
        
        For Each row In tbl.Rows
            
            For Each cell In row.Cells
                
                cellText = cell.Range.Text
                cellText = Replace(cellText, Chr(13), "")
                cellText = Replace(cellText, Chr(7), "")
                
                Select Case cellText
                    Case "1"
                        cell.Shading.BackgroundPatternColor = RGB(0, 176, 80)
                    Case "2"
                        cell.Shading.BackgroundPatternColor = RGB(146, 208, 80)
                    Case "3"
                        cell.Shading.BackgroundPatternColor = RGB(255, 255, 0)
                    Case "4"
                        cell.Shading.BackgroundPatternColor = RGB(255, 0, 0)
                End Select
            
            Next cell
        
        Next row
    
    Next tbl
    
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.