기술공부/개발_코드

엑셀 function: 표에서 원하는 값을 하이라이트하기

넹넹선생님 2024. 7. 29. 15:36
728x90
반응형

 

1. 엑셀 파일을 열고 ALT + F11을 눌러 VBA 편집기를 엽니다.

2.Insert > Module을 클릭하여 새 모듈을 추가합니다.

3. 아래 코드를 복사하여 모듈에 붙여넣습니다.

 

Sub HighlightBestPerformance()
    Dim ws As Worksheet
    Dim rng As Range
    Dim cell As Range
    Dim maxVal As Double
    Dim maxCell As Range
    Dim row As Integer
    Dim col As Integer
    Dim performanceMetrics As Variant
    Dim startRow As Integer
    Dim endRow As Integer
    Dim startCol As Integer
    Dim endCol As Integer

    ' "sheet2" 시트를 변수에 할당
    Set ws = ThisWorkbook.Sheets("sheet2")
    
    ' 성능 지표 배열 (각 행에 대응)
    performanceMetrics = Array("MAE", "MSE", "R2", "MAPE")
    
    ' 표의 시작 및 끝 범위 설정 (여기서는 6행부터 9행, C열부터 G열로 가정)
    startRow = 105
    endRow = 108
    ' startCol = 3
    startCol = 9
    ' startCol = 15
    
    ' endCol = 6
    endCol = 12
    ' endCol = 18
    
    ' 각 성능 지표에 대해 가장 좋은 값을 찾고 하이라이트
    For row = startRow To endRow
        ' MAE, MSE, MAPE는 최소값이 가장 좋음
        If performanceMetrics(row - startRow) = "MAE" Or performanceMetrics(row - startRow) = "MSE" Or performanceMetrics(row - startRow) = "MAPE" Then
            maxVal = ws.Cells(row, startCol).Value
            Set maxCell = ws.Cells(row, startCol)
            For col = startCol To endCol
                If ws.Cells(row, col).Value < maxVal Then
                    maxVal = ws.Cells(row, col).Value
                    Set maxCell = ws.Cells(row, col)
                End If
            Next col
        ' R2는 최대값이 가장 좋음
        ElseIf performanceMetrics(row - startRow) = "R2" Then
            maxVal = ws.Cells(row, startCol).Value
            Set maxCell = ws.Cells(row, startCol)
            For col = startCol To endCol
                If ws.Cells(row, col).Value > maxVal Then
                    maxVal = ws.Cells(row, col).Value
                    Set maxCell = ws.Cells(row, col)
                End If
            Next col
        End If
        ' 가장 좋은 값을 포함한 셀을 노란색으로 하이라이트
        maxCell.Interior.Color = RGB(255, 255, 0)
    Next row

End Sub

 

4. F5 키를 눌러 매크로를 실행하면 "sheet 2" 시트의 각 성능 지표에 대해 가장 좋은 값을 가진 셀이 노란색으로 하이라이트됩니다.

728x90
반응형