Excel单元格值到注释中

时间:2015-02-04 07:23:57

标签: excel vba excel-vba comments

我希望Excel能够自动为一系列单元格创建注释。注释应包含另一个单元格范围的值。 这是我到目前为止所得到的:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim sResult As String

If Union(Target, Range("A18")).Address = Target.Address Then
    Application.EnableEvents = False
    Application.ScreenUpdating = False
    sResult = "Maximal " & Target.Value


    With Range("I6")
        .ClearComments
        .AddComment
        .Comment.Text Text:=sResult
    End With
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End If
End Sub

这适用于一个细胞;我的问题是,我需要这一系列的细胞。 F.E.假设我在单元格A21:F40的注释中需要单元格A1:F20的值。当然,我不想多次复制同一个Sub。

有关如何解决此问题的任何想法?

3 个答案:

答案 0 :(得分:1)

如果你替换

它应该做你的工作
With Range("I6")
        .ClearComments
        .AddComment
        .Comment.Text Text:=sResult
    End With

    For Each cell In Range("A1", "F20").Cells
    Dim V As Range
    Set V = cell.Offset(20, 0)
    With cell
    .ClearComments
    If Not IsEmpty(V) Then
    .AddComment V.Value
    End If
    End With
   Next

这基本上会忽略所有空单元格。

输出:

enter image description here

我的代码:

Sub TEST()
 For Each cell In Range("A1", "F20").Cells
    Dim V As Range
    Set V = cell.Offset(20, 0)
    With cell
    .ClearComments
    If Not IsEmpty(V) Then
    .AddComment V.Value
    End If
    End With
   Next
End Sub

答案 1 :(得分:1)

我对你的建议做了一些调整,非常感谢,这解决了我的问题:

Private Sub Worksheet_Change(ByVal target As Range)


Dim src As Range: Set src = Worksheets("maxleft").Range("C2:K11")
Dim tar As Range: Set tar = Range("I6:Q15")

    For i = 0 To tar.Rows.Count - 1
        For j = 0 To tar.Columns.Count - 1
        Dim sResult As String
        sResult = "Maximal " & Worksheets("maxleft").Cells(src.Row + i, src.Column + j)
        With Cells(tar.Row + i, tar.Column + j)
            .ClearComments
            .AddComment
            .Comment.Text Text:=sResult
        End With
        Next j
    Next i

End Sub

答案 2 :(得分:0)

根据您的问题,我了解您要选择一系列单元格(例如“A1:A5”),然后选择另一个单元格范围(例如“B6:B10”),并且第一个选定范围的相应值应该在secon选定的Range中作为注释放置。这是对的吗?

以下代码检查是否选择了2个长度相等的范围,并将第一个选定范围的值复制为第二个选定范围的注释:

Private Sub Worksheet_SelectionChange(ByVal target As Range)

If InStr(target.Address, ",") Then
    Dim selected_range() As String
    selected_range = Split(target.Address, ",")

    If Range(selected_range(0)).Rows.Count = Range(selected_range(1)).Rows.Count Then
        Dim src As Range: Set src = Range(selected_range(0))
        Dim tar As Range: Set tar = Range(selected_range(1))

        For i = 0 To src.Rows.Count - 1
            Dim sResult As String
            sResult = "Maximal " & Cells(src.Row + i, src.Column)
            With Cells(tar.Row + i, tar.Column)
                .ClearComments
                .AddComment
                .Comment.Text Text:=sResult
            End With
        Next i
    End If
End If
End Sub