简体   繁体   中英

Check if a cell value in a row exceeds a certain value

I want to check in excel whether any cell value in a given row (eg row 6) exceeds 40. I wrote this:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim cell As Range

    For Each cell In ActiveSheet.Rows(6)
        If cell.Value > 40 Then MsgBox "You exceeded 40 in cell: " & cell.Address & ". Please correct your input!"
    Next cell

End Sub

But it gives me an error message

Runtime error 13, Type mismatch.

Could you please advise? Thanks.

to get every cell, change your for -loop to

For Each cell In ActiveSheet.Rows(6).Cells

However, this will check the complete 6th row every time you change anything anywhere in the sheet. I guess it would be better to simply check the value of Target - this is the cell that is currently modified by the user.

Update You could change your routine to

Private Sub Worksheet_Change(ByVal Target As Range)
    If target.row = 6 && Target.Value > 40 Then 
        MsgBox "You exceeded 40 in target: " & target.Address & ". Please correct your input!"
    endif
End Sub

But if you simply want to prevent that the user enters some value greater than 40, you can easily archive this without VBA by using data validation :

Mark row 6, choose Data -> Data Validation -> Data Validation

Enter for example "Whole number" (or decimal if you want to allow comma values), "less than or equal to" and 40 as maximum.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM