以下代码是一个更改事件处理程序,它在 col B 中搜索单词“fee”,如果在 col B 中找到单词“fee”,则在 3 个相邻的 col 中插入注释:
Private Sub Worksheet_Calculate()
Dim rng As Range, cell As Range
Set rng = Range("B:B")
If Not rng Is Nothing Then
For Each cell In rng.Cells
If cell.Value = "fee" Then
cell.Offset(0, 1).AddComment "fi"
cell.Offset(0, 2).AddComment "fo"
cell.Offset(0, 3).AddComment "fum"
End If
Next
End If
End Sub
上面的代码工作正常。
如果col B中没有出现“fee”这个词,我还想搜索col B并删除3个相邻cols中的任何现有评论。所以,我添加了一个Else语句:
Private Sub Worksheet_Calculate()
Dim rng As Range, cell As Range
Set rng = Range("B:B")
If Not rng Is Nothing Then
For Each cell In rng.Cells
If cell.Value = "fee" Then
cell.Offset(0, 1).AddComment "fi"
cell.Offset(0, 2).AddComment "fo"
cell.Offset(0, 3).AddComment "fum"
Else:
cell.Offset(0, 1).Comment.Delete
cell.Offset(0, 2).Comment.Delete
cell.Offset(0, 3).Comment.Delete
End If
Next
End If
End Sub
这会导致运行时错误:“Object variable or With block variable not set”,调试器指向
cell.Offset(0, 1).Comment.Delete
VBA 似乎希望我使用 With 语句,但我尝试过的 With 排列会导致相同的错误。有什么想法吗?
跟进安迪的正确建议。如果满足条件,代码添加注释,如果不满足,则清除注释:
Private Sub Worksheet_Calculate()
Dim rng As Range, cell As Range
Set rng = Range("B:B")
If Not rng Is Nothing Then
For Each cell In rng.Cells
cell.Offset(0, 1).ClearComments
cell.Offset(0, 2).ClearComments
cell.Offset(0, 3).ClearComments
If cell.Value = "fee" Then
cell.Offset(0, 1).AddComment "fi"
cell.Offset(0, 2).AddComment "fo"
cell.Offset(0, 3).AddComment "fum"
End If
Next
End If
End Sub