将注释和颜色插入满足If … Then语句的单元格中

所以我基本上试图插入一个评论和颜色基本上符合我在我的代码中设置的标准的单元格。 我search了一切,但似乎找不到一个可行的解决scheme。

这里是我到目前为止的代码,我在下面的代码中提到我想要的颜色和评论。 我有这个macros设置的方式是从工作表中“调用”。 我使用了Selection_Changefunction。 所以我有一个范围,在一列中有人input数据,然后input任何数据在下面的macros运行,并检查是否在限制之内。

如果它不在excel表格(“M7”和“M19”)中设置的范围内,我想要一个颜色来突出显示某个单元格和该单元格中的设置注释。 我将如何去做这件事? 我真的很感激帮助。 谢谢!

此外,我在网上find了一个代码,我的问题是,当我使用

ActiveCell.AddComment ("Text") 

我一直收到一个错误,而且在我input数据点之后,我按下回车键,注释进入下一个单元格。

这是被调用的macros:

  Option Explicit Public Sub OutofControlRestofData() Dim lRow As Long Dim lstRow As Long Dim data As Variant Dim ul As Variant Dim ll As Variant Dim wb As Workbook Dim ws As Worksheet With Application .ScreenUpdating = True .EnableEvents = True .DisplayAlerts = True End With Set ws = Sheets(2) ws.Select lstRow = WorksheetFunction.Max(1, ws.Cells(Rows.Count, "R").End(xlUp).Row) For lRow = 1 To lstRow data = Cells(lRow, "E").Value ul = Range("M7") ll = Range("M19") If data > ul Or data < ll Then If IsNumeric(data) = True And data Like "" = False Then MsgBox ("There was an Out of Control Point at " & Cells(lRow, "C").Value) 'THIS IS WHERE I THINK THE COMMENTING AND COLOR CODE WOULD BE End If End If Next lRow End Sub 

另外这里是调用macros的代码:

 Private Sub Worksheet_Change(ByVal Target As Range) If Not Intersect(Target, Target.Worksheet.Range("E39:E138")) Is Nothing Then Run ("OutofControlRestofData") End If End Sub 

有几件事要注意。

  1. 你应该练习使用tab来嵌套你的If语句。 使其看得更清楚。
  2. 你可以继续并结合这两个子。 只要确保将代码放在工作表代码页中(而不是在工作簿模块中)。
  3. 如果您已经有了“ Target ”,那么您不需要循环,因为这是您想要检查的单元格(范围)。
  4. 您已经定义了“变更”子项,只有在数据项在E39E138之间时才能使用。 这会一直如此吗? 考虑使用整个column E如果你想更灵活地增长你的工作表和数据。

码:

 Private Sub Worksheet_Change(ByVal Target As Range) Dim ws As Worksheet Set ws = Sheets(2) If Not Intersect(Target, ws.Range("E39:E138")) Is Nothing Then Dim lRow As Long Dim lstRow As Long Dim data As Variant Dim ul As Variant Dim ll As Variant Dim wb As Workbook Dim ws As Worksheet With Application .ScreenUpdating = True .EnableEvents = True .DisplayAlerts = True End With data = Target.Value ul = Range("M7").Value ll = Range("M19").Value If data > ul Or data < ll Then If IsNumeric(data) = True And data Like "" = False Then MsgBox ("There was an Out of Control Point at " & Target.Address) Target.Interior.Color = RGB(255, 0, 0) Target.AddComment ("This is an Out of Control Point") End If End If End If End Sub 

为了安全起见,我build议在这里改变你的代码以包含value

 data = Range("E" & lRow).Value ul = Range("M7").Value ll = Range("M19").Value 

然后在你想要做的颜色/评论的地方:

 Range("E" & lRow).Interior.Color = RGB(255, 0, 0) Range("E" & lRow).AddComment("This is an Out of Control Point")