0

I have a question about VBA in Excel as I am getting #value! error in Excel. I would like to change background color of cell (that is not an argument of a function but is being searched in For loop), i.e. prerequisite_cell and return string in the Cell.

Public Function PrerequisitesOK(no_groups_cell As Range) As String
    Application.Volatile
    Dim cw As Worksheet
    Dim prerequisites As Range
    Dim prerequisites_add As String
    Dim prerequisite_cell As Range
    Dim prerequisite_cell_col As Interior
    Dim prerequisite_cell_txt As String
    Dim training_id As Range
    Dim training_id_cell As Range
    Dim no_groups_cell_val As Double
    Dim no_groups_cell_to_check As Range
    Dim training_id_cell_txt As String
    Dim training_id_cell_row_n As Integer
    Dim n As Integer
    Dim no_groups_cell_row_n As Integer

    PrerequisitesOK = "OK"
    
    Set cw = Sheets("4c.Trainings OSS")
    
    Set training_id = cw.Range("B11:B34")
    
    no_groups_cell_row_n = no_groups_cell.Row
    
    no_groups_cell_val = no_groups_cell.Value
    
    prerequisites_add = "D" + CStr(no_groups_cell_row_n) + ":H" + CStr(no_groups_cell_row_n)
    Set prerequisites = cw.Range(prerequisites_add)
    
    For Each prerequisite_cell In prerequisites.Cells
        prerequisite_cell_txt = prerequisite_cell.Text
        If prerequisite_cell_txt = "" Then
            Exit For
        Else
            For Each training_id_cell In training_id.Cells
                training_id_cell_txt = training_id_cell.Text
                If training_id_cell_txt = prerequisite_cell_txt Then
                    training_id_cell_row_n = training_id_cell.Row
                    Set no_groups_to_check = cw.Cells(training_id_cell_row_n, no_groups_cell.Column)
                    If no_groups_to_check.Value < no_groups_cell_val Then
                        prerequisite_cell.Interior.Color = RGB(255, 0, 0)
                        PrerequisitesOK = "Not OK"
                    End If
                    Exit For
                End If
            Next training_id_cell
        End If
    Next prerequisite_cell
End Function

The function is returning error while executing this line:

Set prerequisite_cell.Interior.Color = RGB(255, 0, 0)

Can anyone explain me why? I can not make any changes to searched objects?

John Snow
  • 107
  • 1
  • 10
  • 2
    There are some workarounds, e.g. [this](https://stackoverflow.com/questions/23433096/using-a-udf-in-excel-to-update-the-worksheet), but generally a user-defined function called from the worksheet can't modify another cell. – BigBen Nov 24 '21 at 15:59
  • 1
    No `Set` in `Set prerequisite_cell.Interior.Color = RGB(255, 0, 0)` btw. – BigBen Nov 24 '21 at 15:59
  • 1
    Side note: `"D" + CStr(no_groups_cell_row_n) + ":H" + CStr(no_groups_cell_row_n)` - change those `+` to `&`. Prefer `&` for concatenation.. – BigBen Nov 24 '21 at 16:00

0 Answers0