I've looked at the similar questions about "Method of Object Range Failed" but none seem to help me solve my problem.
The error I receive is: "Method 'ClearContents' of Object Range Failed"
Essentially what I'm trying to achieve is that if cell value of BG21 = 1 And the length of the string in adjacent cell (BH21) is 0 Then timestamp the adjacent cell (BH21). Ideally I want to repeat this for Range (BG21:BG35). I know I could use a for each method but I want to get this error cleared first.
I don't want to use the cell formula because I need a timestamp the moment the cell BG21 changes to 1. If I use a cell formula then anytime the workbook is opened the timestamp changes.
The code I have is:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim wb As Workbook, ws As Worksheet
Set wb = ThisWorkbook
Set ws = wb.Worksheets("Submittal Kickoff Meeting")
If (ws.Range("$BG$21").Value = 1 And len(ws.Range("$BH$21").Value) = 0 And Target.Address = ws.Range("$BG$21")) Then
ws.Range("$BH$21").Value = Format(Now(), "m/dd/yyyy hh:mm:ss AM/PM")
Else
ws.Range("$BH$21").ClearContents '<--- Error occurs here
End If
End Sub
The error occurs on line:
ws.Range("$BH$21").ClearContents
I have also tried:
ws.Range("$BH$21").Value = ""
But I received the same error code
Any advice??
.
I couldn't get the error, but there are two things in your code you made wrong.
Target.Address = ws.Range("$BG$21")
Default property for Range
is Value
, so you compare Address with Value here. ws.Range("$BH$21").ClearContents
will cause infinite loop, as this code changes worksheet, so Change
event occurs and macro starts again. Use EnableEvents
to avoid this.
Application.EnableEvents = False ws.Range("$BH$21").ClearContents Application.EnableEvents = True
You have it cycling through an infinite loop due to you editing the file when you change the value of BH21. You will need another if or something else to avoid the infinite loop. Mine worked just fine with editing cell with a blank.
You should also change your if statement from
Target.Address = ws.Range("$BG$21")
to
Target.Address = "$BG$21"
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.