excel 这个VBA代码哪里出错了?--条件格式

lbsnaicq  于 2022-12-14  发布在  其他
关注(0)|答案(1)|浏览(140)

I am a VBA beginner I am trying to build a simple comparison function which will compare two adjacent cells in Excel and return desired text values as output. Moreover I want to format the second cell according to the output.
The first part works well but the formatting part is giving me a hard time.

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

How to correctly write the following line of code? Cell2.Interior.Color = RGB........

gzszwxb4

gzszwxb41#

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

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

相关问题