评论细胞

Commenting on cells

所以我有一些代码可以根据旁边的信息对单元格进行评论,而且它几乎可以完美地工作。但是,我遇到了一个问题,它正在处理整个工作簿中的所有 sheet,而不是像预期的那样只处理 sheet 3。我仅在 VBA 项目中在 sheet 3 上设置了此代码。所以我的问题是我怎样才能让这个只在一个 sheet 上工作? 这是我的代码

Private Sub Worksheet_Calculate()

ActiveSheet.UsedRange.ClearComments

Dim targetRng As Range, commentSrcRng As Range
Dim strPrefix As String 'string Prefix

Set targetRng = Application.Range("D16,D18,D20,D22,D24,D26,D28,D30,D32,D34,D36,D38")
Set commentSrcRng = targetRng.Offset(0, 1)

Dim cel As Range
Dim i As Long
i = 1
    For Each cel In targetRng
        If cel <> "" Then
            cel.AddComment
                cel.Comment.Visible = False
                cel.Comment.Shape.TextFrame.AutoSize = True
                cel.Comment.Text strPrefix & commentSrcRng.Cells(i)
        End If
            i = i + 2
    Next

However, I am having an issue where it is working on all sheets in the entire workbook

那是因为您已对其进行编码以在 ActiveSheet

上运行

要引用 sheet 事件编码,请使用 Me

Private Sub Worksheet_Calculate()
    Me.UsedRange.ClearComments

    Dim targetRng As Range, commentSrcRng As Range
    Dim strPrefix As String 'string Prefix

    Set targetRng = Me.Range("D16,D18,D20,D22,D24,D26,D28,D30,D32,D34,D36,D38")
    Set commentSrcRng = targetRng.Offset(0, 1)

    Dim cel As Range
    Dim i As Long
    i = 1
    For Each cel In targetRng
        If cel <> "" Then
            cel.AddComment
            cel.Comment.Visible = False          cel.Comment.Shape.TextFrame.AutoSize = True
            cel.Comment.Text strPrefix & commentSrcRng.Cells(i)
        End If
        i = i + 2
    Next
End Sub