问题
I have an excel sheet that should behave a specific way.
For example the cells I11 - I20 are user input cells in the form of a drop down.
For these cells I need to monitor if a user selects a value that is less than the number 900.
If a user selects a number less than 900 for cell I11 for example, I need to set cells K11 formula to = J11.
If a user selects a number greater than 900, then i clear the formula and allow the cell to be user input.
I need to do this for all cells that range from I11-I20.
Here is what i have for one cell, however i get an error that states "Object variable or With block variable not set" and this only allows me to change one row.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim A As Range
Set A = Range("I11")
If Intersect(Target, A) > 900 Then A.Offset(0, 2).Value = ""
Application.EnableEvents = False
A.Offset(0, 2).Value = "=J11"
Application.EnableEvents = True
End Sub
Thank you for any assistance.
回答1:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Cells.Count = 1 Then
If Not Intersect(Target, Range("I11:I20")) Is Nothing Then
Application.EnableEvents = False
If Target > 900 Then
Target.Offset(0, 2).ClearContents
Else
Target.Offset(0, 2).Formula = "=J" & Target.Row
End If
Application.EnableEvents = True
End If
End If
End Sub
回答2:
You have already indicated the target.range, enable events would not be required. You would not require the formula, just make the cell equal the other cell.
So if there is a change in Column I And the value is >900, blank the cell 2 columns over. If the change is <=900 then make the cell two columns over equal to the cell 1 column over.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Count > 1 Then Exit Sub ' this stops code error if more than one cell is changed at once
If Not Application.Intersect(Target, Me.Range("I1:I100")) Is Nothing Then ' indicates the Target range
If Target > 900 Then
Target.Offset(, 2) = ""
Else: Target.Offset(, 2).Value = Target.Offset(, 1).Value
End If
End If
End Sub
来源:https://stackoverflow.com/questions/50630660/excel-vba-worksheet-change-monitoring