根据输出格式化单元格颜色

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

我构建了一个函数,它将比较 Excel 中的两个相邻单元格并返回文本值作为输出。

我想根据输出格式化第二个单元格。

Function COMPARE(ByVal Cell1 As Range, ByVal Cell2 As Range) As String
Dim Result As String
If Cell1 = Cell2 Then
    COMPARE = ""
ElseIf Cell1 > Cell2 Then
    COMPARE = "Kapa-Reduzierung"
    Cell2.Interior.Color = RGB(255, 153, 153)
ElseIf Cell1 < Cell2 Then
    COMPARE = "Kapa-Erhöhung"
    Cell2.Interior.Color = RGB(255, 255, 204)
Else: COMPARE = "Input Error"
End If
End Function

下面的怎么写?

Cell2.Interior.Color = RGB........
excel vba function if-statement user-defined-functions
1个回答
0
投票

这个怎么样? (更改工作簿名称、工作表名称和单元格范围以满足您的要求。)

Private strCOMPARE As String

Sub CheckCells(ByVal Cell1 As Range, ByVal Cell2 As Range)
    
    If Cell1.Value = Cell2.Value Then
        
        strCOMPARE = ""
        
    Else
        
        If Cell1 > Cell2 Then
            
            strCOMPARE = "Kapa-Reduzierung"
            
            Cell2.Interior.Color = RGB(255, 153, 153)
            
        Else
            
            If Cell1 < Cell2 Then
                
                strCOMPARE = "Kapa-Erhohung"
                
                Cell2.Interior.Color = RGB(255, 255, 204)
                
            Else
                
                strCOMPARE = "Input Error"
                
            End If
            
        End If
        
    End If
    
End Sub

Sub Test()
    
    With Workbooks("Book1").Worksheets("Sheet1")
        
        Call CheckCells(.Range("A1"), .Range("B1"))
        
    End With
    
    MsgBox strCOMPARE
    
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.