VBA: Tự động thêm Comment vào ô bằng cách dò tìm dữ liệu từ Sheet khác

Tình huống:đây là 1 request thực tế từ sếp cũ của mình, thêm comment cho 1 bảng tính, nhưng việc add comment cho từng ô thật sự rất phiền phức và vất vả nên mình đã tạo nên sub này.


Range add comment:A2:A10

Range dò comment:sheet data cột B, nội dung comment ở cột C

Sub AddComment1()
Dim r As Excel.Range
Dim c As Excel.Range
Set Rng = ActiveSheet.Range("A2:A10")
For Each c In Rng
With c
Set r = Sheets("Data").Range("B:B").Find(What:=.Value, Lookat:=xlWhole, MatchCase:=False)
If Not r Is Nothing Then
.ClearComments
.AddComment
.Comment.Visible = False
.Comment.Text r.Offset(, 1).Value 'lấy nội dung cột C
.Comment.Shape.TextFrame.AutoSize = True
End If
End With
Next c
End Sub



Range add comment:selected cells

Range dò comment:sheet data cột B, nội dung comment ở cột C

Sub AddComment2()
    Dim r As Excel.Range
    Dim c As Excel.Range
    Dim Rng As Excel.Range ' Thêm Dim này cho chuẩn

    Set Rng = Selection ' Thay A2:A10 thành Selection ở đây

    For Each c In Rng
        With c
            Set r = Sheets("Data").Range("B:B").Find(What:=.Value, Lookat:=xlWhole, MatchCase:=False)
            If Not r Is Nothing Then
                .ClearComments
                .AddComment
                .Comment.Visible = False
                .Comment.Text r.Offset(, 1).Value 'lấy nội dung cột C
                .Comment.Shape.TextFrame.AutoSize = True
            End If
        End With
    Next c
End Sub

Nhận xét